Using javascript to automatically put the cursor in the first field of a form

When creating a form for use on a webpage, it may be desirable to have the cursor automatically appear in a certain field. To do this requires a bit of javascript. This example is from a CGI script that creates the form.

#!/usr/bin/perl use CGI qw(:standard); print header(); print start_html("CookieMonster"); print <<EndOfHTML; <FORM ACTION="/cgi-bin/setloginidcookie.cgi" name="form" METHOD="POST"> <body bgcolor="#FFCF10" topmargin="0" leftmargin="0" onload="document.form.loginID.focus()"> &nbsp;<p> <h4>&nbsp;&nbsp;Please enter your login ID. This is the same as your network login. A password is not necessary.</h4><p> &nbsp;&nbsp;<input type="text" name="loginID" tabindex="1"> <input type="submit" value="Enter" tabindex="2"> </form> <script type="text/javascript"> </script> EndOfHTML print end_html;

Here are the key points:

  • The form has to have a name--see the 'name="form"' part.
  • In the body of the form, use the 'onload' directive. The syntax for the value is the word 'document' followed by the name you gave the form, followed by the name you gave the desired field, followed by 'focus(), all connected with dots.
  • Somewhere in the form, declare javascript as the script type used.
  • 03/24/2005