tarunkhanna has asked for the wisdom of the Perl Monks concerning the following question:

Hi

I am running the below code.

use CGI; my $co = new CGI; use CGI qw(:standard); use CGI::Carp qw(fatalsToBrowser); use strict; use diagnostics; print $co->header; print $co->start_html(); print $co->start_form; print $co->h4("Name").$co->p; print $co->textfield('name').$co->p; print <<CheckNameBox; <script language="JavaScript"> function CheckForEmptyTextbox() { alert(document.getElementById("name").value); } // end function </script> CheckNameBox print $co->submit(-onclick=>"CheckForEmptyTextbox()"); print $co->reset; print $co->end_form; print $co->end_html;
In the above code, alert box doesn't appear on clicking submit button with or without any value in "name" text box.
use CGI; my $co = new CGI; use CGI qw(:standard); use CGI::Carp qw(fatalsToBrowser); use strict; use diagnostics; print $co->header; print $co->start_html(); print $co->start_form; print $co->h4("Name").$co->p; print $co->textfield('name').$co->p; print <<CheckNameBox; <script language="JavaScript"> function CheckForEmptyTextbox() { alert("hello"); } // end function </script> CheckNameBox print $co->submit(-onclick=>"CheckForEmptyTextbox()"); print $co->reset; print $co->end_form; print $co->end_html;

But in the 2nd code, alert box appears. May be in the 1st code, document.getElementById("name").value is not able to pick the value from textbox. Why alert box not appearing in the first code or what steps shall i take to make alert box working in the first code with the value in name textbox.

Replies are listed 'Best First'.
Re: Javascript with CGI
by marto (Cardinal) on Oct 07, 2011 at 08:27 UTC

    This isn't a perl problem. Get your HTML/JavaScript working the way you want before embeding it in your Perl script. Personally I prefer to keep HTML/css/JavaScript separate from my perl code by using one of the templating modules. See HTML::Template or Template::Toolkit.

Re: Javascript with CGI
by Anonymous Monk on Oct 07, 2011 at 06:30 UTC

    Why alert box not appearing in the first code or what steps shall i take to make alert box working in the first code with the value in name textbox.

    Because you're not paying attention :)

    See CGI button -onClick not working

    Examine the generated HTML and you'll see there is no id='name'

    $ perl -MCGI -le " print CGI->textfield(q[name]) " <input type="text" name="name" />
    A reply falls below the community's threshold of quality. You may see it by logging in.