Generating JavaScript from Perl
by Stephen B. Jenkins

Listing One
# create a static JavaScript function that opens the new browser window
my $JSmakepage = <<EOF;
    function makepage(filename) {
        newwin = window.open('displayfile.pl?FILE=' + filename);
        newwin.focus();
    }    
EOF
# ... lots of missing code ...
# create buttons to use JS code, generating passed parameter dynamically
my $button = '<INPUT ' . 
             'TYPE="button" ' .
             'NAME= "' . $buttonname .  '" ' .
             'VALUE="' . $buttonvalue . '" ' .
             'onClick="makepage(\'' . $filename . '\')" ' .
             '>';


Listing Two
#!/usr/bin/perl -wT
use strict;
use CGI qw(:standard);

my $groupname = 'machines';
my @machinenames = qw( This should really be a list of computer names );

# generate the JavaScript and HTML
my $js = &createJSfuncs($groupname, @machinenames);
my $html = &createHTMLcheckboxes($groupname, @machinenames);

# send the JS and HTML to the browser
print header,
      start_html( -title  => 'DDJ checkbox example',
                  -script => {-language=>'JavaScript', -code=>$js} ),
      start_form(), 
      $html, 
      end_form(),
      end_html();

# create the JavaScript 'check all' and 'check none' functions
sub createJSfuncs {
    my $groupname = shift;      # the name of the checkbox group
    my @boxnames =  @_;         # the list of checkbox names
    my $all =  "function ${groupname}_all()  {\n";
    my $none = "function ${groupname}_none() {\n";

    foreach (@boxnames) {
        $all .=  "\tself.document.forms[0].$_.checked = true;\n";
        $none .= "\tself.document.forms[0].$_.checked = false;\n";
    }
    $all .= "}";
    $none .= "}";   
    return("\n$all\n$none\n");
}
# create the HTML for a group of checkboxes with all & none buttons
sub createHTMLcheckboxes {
    my $groupname = shift;      # the name of the checkbox group
    my @boxnames =  @_;         # the list of checkbox names
    my $checkboxgroup = '';

    foreach (@boxnames) {
        $checkboxgroup .= checkbox( -name=> $_ ) . "<BR>\n";
    }    
    $checkboxgroup .= button( -name    => "${groupname}allbutton", 
                              -value   => 'Check All',
                              -onClick => "${groupname}_all()" ) . "\n" .
                      button( -name    => "${groupname}nonebutton", 
                              -value   => 'Clear All',
                              -onClick => "${groupname}_none()" ) . "\n";
    return($checkboxgroup);
}




2

