Using JavaScript and forms

Of all the hats JavaScript can wear, its form processing features are among the most sought and used

1 2 Page 2
Page 2 of 2

Listing 5. form_textarea.html

<HTML> <HEAD> <TITLE>Text Area Test</TITLE> <SCRIPT LANGUAGE="JavaScript"> function seeTextArea (form) { alert (form.myarea.value);

} </SCRIPT> </HEAD> <BODY> <FORM NAME="myform"> <INPUT TYPE="button" NAME="button3" Value="Test" onClick="seeTextArea(this.form)"> <TEXTAREA NAME="myarea" COLS="40" ROWS="5"> </TEXTAREA> </FORM> </BODY> </HTML>

You can preload text into the text area in either of two ways. One method is to enclose text between the <TEXTAREA> and </TEXTAREA> tags. This method is useful if you wish to include hard returns, as these are retained in the text area box. Or, you can set it programmatically with JavaScript using the following syntax:

form.textarea.value = "Text goes here";
  • form is the name of the form.
  • textarea is the name of the textarea.
  • "Text goes here" is the text you want to display

Using Selection Lists

List boxes let you pick the item you want out of a multiple-choice box. The listbox itself is created with the <SELECT> tag, and the items inside it are created by one or more <OPTION> tags. You can have any number of <OPTION> tags in a list. The list is terminated with a </SELECT> tag.

The list can appear with many items showing at once, or it can appear in a drop-down box -- normally you see one item at a time, but click to see more. The markup for the two styles is identical, except for the optional SIZE attribute. Leave off SIZE to make a drop-down box; use SIZE to make a list box of the size you wish.

Use the selectedIndex property to test which option item is selected in the list, as shown in the following example. The item is returned as an index value, with 0 being the first option, 1 being the second, and so forth (if no item is selected the value is -1).

Listing 6. form_select.html

<TITLE>List Box Test</TITLE>
function testSelect(form) {
    alert (form.list.selectedIndex);
<INPUT TYPE="button" NAME="button" Value="Test" onClick="testSelect(this.form)">
<SELECT NAME="list" SIZE="3">
<OPTION>This is item 1
<OPTION>This is item 2
<OPTION>This is item 3

If you want the text of the selected list item instead of the index, use this in the testSelect function:

function testSelect (form) {
    Item = form.list.selectedIndex;
    Result = form.list.options[Item].text;
    alert (Result);

Other events you can trigger within a form

I've used the onClick event handler in all of the examples because that's the one you are most likely to deal with in your forms. Yet JavaScript supports a number of other event handlers as well. Use these as the need arises, and the mood fits. In Navigator 2.x The event handlers used with form object are:

  • onFocus -- an event is triggered with a form object gets input focus (the insertion point is clicked there).
  • onBlur -- an event is triggered with a form object loses input focus (the insertion point is clicked out of there).
  • onChange -- an event is triggered when a new item is selected in a list box. This event is also trigged with a text or text area box loses focus and the contents of the box has changed.
  • onSelect -- an event is triggered when text in a text or text area box is selected.
  • onSubmit -- an event is triggered when the form is submitted to the server (more about this important hander later in the column).

Submitting the form to the server

In the examples above I've limited the action of the form to within JavaScript only. Many forms are designed to send data back to a CGI program runnong on the server. This is referred to as submitting the form, and is accomplished using either of two JavaScript instructions: the onSubmit event handler or the submit method. In most instances, you use one or the other, not both!

  • Place the onSubmit event hander in the <FORM> tag. This tells JavaScript what it should do when the user clicks the Submit button (this is a button defined as TYPE="submit").
  • Place the submit instruction anywhere in your JavaScript. It can be activated by any action, such as clicking a form button that has been defined with the onClick event handler.

Using onSubmit

Here's an example of using the onSubmit event handler to send mail. The onSubmit event handler tells JavaScript what to do when the user clicks the Submit button: call the mailMe() function, where additional mail fields are appended to a mailto: URL. Navigator automatically opens a new mail window with the fields filled in. Write the body of the message, and send the mail off to the recipient.

Listing 7. onsubmit.html

<TITLE>onSubmit Test</TITLE>
function mailMe(form){
    CC= document.testform.inputbox2.value;
    BCC= document.testform.inputbox3.value;
    location = ""+Subject+"&Bcc="+
    return true;
<FORM NAME="testform" onSubmit="return mailMe(this.form)" >Subject of message: <BR>
<INPUT TYPE="text" NAME="inputbox1" VALUE="This is such a great form!" SIZE=50>
<P>Send cc to: <BR>
<INPUT TYPE="text" NAME="inputbox2" VALUE="" SIZE=50><P>
Send blind cc to: <BR>
<INPUT TYPE="text" NAME="inputbox3" VALUE="" SIZE=50><P>
<INPUT TYPE="submit"><BR>

Using submit

In the next example the submit method is used instead. The script is little changed, except that the onSubmit handler is removed, and an onClick hander for a renamed form button is added in its place. The submit() method replaces the return true statement in the previous example. (Personally, I prefer the submit method because it provides a little more flexibility. But either one will work.)

Listing 8. submit.html

function mailMe(form){
    CC= document.testform.inputbox2.value
    BCC= document.testform.inputbox3.value
    location = "/javaworld/cgi-bin/jw-mailto.cgi?"+Subject+"&Bcc="+
<FORM NAME="testform">
Subject of message: <BR>
<INPUT TYPE="text" NAME="inputbox1" VALUE="This is such a great form!" SIZE=50><P>
Send cc to: <BR><INPUT TYPE="text" NAME="inputbox2" VALUE="" SIZE=50><P>
Send blind cc to: <BR><INPUT TYPE="text" NAME="inputbox3" VALUE="" SIZE=50><P>
<INPUT TYPE="button" VALUE="Send Mail" onClick="mailMe()"><BR>

Validating form data using JavaScript

The World Wide Web "grew up" when they added the ability to display forms. In the days before forms, the Web was only mildly interactive, with just hypertext links to take readers from location to location. Forms allow users to truly interact with the Web. For example, readers can specify search queries using a simple one-line text box.

The typical form as used on a Web page consists of two parts: the form itself, which is rendered in the browser, and a CGI script or program located on the server. This script processes the user's input. While it's not exactly rocket science, a stumbling block in creating great Web forms is writing the CGI program. In most cases these programs are written in Perl or C, and can be a bother to implement and debug. A primary job of the CGI program is to validate that the reader has provided correct data, and this can requires pages of code.

JavaScript changes that. With JavaScript you can check the data provided by the reader before it's ever sent to the CGI program. In this way the CGI program can be kept to a bare minimum. And, because the data is only sent after it has been validated, the server need not be bothered until the form entry is known to be good. This saves valuable server resources.

Most form validation chores revolve around basic data checking: does the user remember to fill in an box? Is it have the right length? Does it contain valid characters? With most forms you can readily answer these questions with a small handful of validation routines.

A typical validation routine is determining if an input box contains only numeric digits, shown below. If the entry contains non-numeric characters, you can ask the user to enter the correct data. A ready-made routine for this is the isNumberString function, which returns the value 1 if the string contains only numbers, and 0 if it contains any non-numeric characters. To use it, provide the data string as the parameter. The value returned by the function tells you if the data is valid.

Listing 9. valid_simple.html

<HTML> <HEAD> <TITLE>Test Input Validation</TITLE> <SCRIPT LANGUAGE="JavaScript"> function testResults (form) { TestVar = isNumberString (form.inputbox.value) if (TestVar == 1) alert ("Congratulations! You entered only numbers"); else alert ("Boo! You entered a string with non-numbers characters"); }

function isNumberString (InString) { if(InString.length==0) return (false); var RefString="1234567890"; for (Count=0; Count < InString.length; Count++) { TempChar= InString.substring (Count, Count+1); if (RefString.indexOf (TempChar, 0)==-1) return (false); } return (true); } </SCRIPT> </HEAD> <BODY> <FORM NAME="myform"> Enter a string with numbers only: <INPUT TYPE="text" NAME="inputbox" VALUE=""> <INPUT TYPE="button" NAME="button" Value="Click" onClick="testResults(this.form)" > </FORM> </BODY> </HTML>


The traditional way to use forms on a Web page is to send all the user's entries to a CGI script or program running on the server. The bulk of most any CGI program is verifying that the user entered valid data. Entry validation is something JavaScript can do, and do very easily. By using JavaScript you can greatly reduce the complexity of writing and implementing CGI programs. And, in many cases JavaScript, can completely supplant CGI programs, taking the burden off the server by relieving it of mundane processing chores.

Gordon McComb is an author, consultant, and lecturer. He has written 50 books and over a thousand magazine articles during his 20 years as a professional writer. More than a million copies of his books are in print. Gordon also writes a weekly syndicated newspaper column on computers, reaching several million readers worldwide. Gordon's latest book is The JavaScript Sourcebook, forthcoming from Wiley Computer Publishing.

This story, "Using JavaScript and forms" was originally published by JavaWorld.

Copyright © 1996 IDG Communications, Inc.

1 2 Page 2
Page 2 of 2