How to open a new page with Perl CGI popup menu

Viewed 453

I wish, from the Perl-cgi script below, to open a new page when we select an item in the menu; as we do with window.open. If anyone has an idea on how I can execute a command similar to : window.open('http://www.google.com', '_blank', 'toolbar=0,location=0,menubar=0');

thank you in advance

#!/usr/bin/perl -Tw
use strict;
use warnings;
use utf8;
use CGI ;
my $cgi = new CGI;
my %url = (
    "https://www.google.com"    => "google" ,
    "https://www.msn.com"       => "msn",
    "https://www.yahoo.com"     => "yahoo" 
);
print $cgi->header("text/html;charset=UTF-8");
print "<!DOCTYPE html>";
print "<html>\n";
print "<head>\n";
print "</head>\n";
print "<body>\n";
print '<form>'."\n";
print $cgi->popup_menu(
  - name     => 'url',
  - id       => 'url',
  - values   => [sort keys %url],
  - default  => ['google'],
  - labels   => \%url,
  - onchange => 'submit();'
    #- onchange => "this.form.submit();"
);
print "</form>\n";
print "</body>\n";
print "</html>\n";
1 Answers

You nearly have it, but you probably want this.value.

print $cgi->popup_menu(
  - name     => 'url',
  - id       => 'url',
  - values   => [sort keys %url],
  - default  => ['google'],
  - labels   => \%url,
  - onchange => q{window.open(this.value, '_blank', 'toolbar=0,location=0,menubar=0');},
);

But as I commented, since these CGI methods are deprecated, please do consider using an alternative such as Template::Toolkit. A common pattern in TT is to have two files that might look as follows.

The Perl file:

#!/usr/bin/perl -Tw

# my_form.cgi

use strict;
use warnings;
use utf8;
use HTTP::Headers;
use Template;

my $headers = HTTP::Headers->new;
$headers->header('Content-Type' =>  'text/html;charset=UTF-8');
print $headers->as_string;

my %urls = (
    "https://www.google.com"    => "google" ,
    "https://www.msn.com"       => "msn",
    "https://www.yahoo.com"     => "yahoo" 
);

my $template = Template->new;
$template->process('my_form.ttml', { urls => \%urls });

The Template file:

[%# my_form.ttml %]
<!DOCTYPE html><html>
<head>
</head>
<body>
<form>
  <select name="url"  id="url" onchange="window.open(this.value, '_blank', 'toolbar=0,location=0,menubar=0');">
    [% FOREACH url IN urls -%]
      <option value="[% url.key %]">[% url.value %]</option>
    [% END -%]
  </select>
</form>
</body>
</html>

You can look at Template::Manual and Template::Manual::Intro for details on Template::Toolkit, or you can look at CGI::Alternatives for more inspiration.

Related