11. Getting Data with Forms

wax ka badal

The Basics of HTML Forms

wax ka badal

Forms are among the most useful features of the HTML language. As you'll learn during this hour, adding JavaScript to forms can make them more interactive and provide a number of useful features. The first step in creating an interactive form is to create the HTML form itself.

Defining a Form

wax ka badal

An HTML form begins with the <form> tag. This tag indicates that a form is beginning, and it enables form elements to be used. The <form> tag includes several attributes:

  • name is simply a name for the form. You can use forms without giving them names, but you'll need to assign a name to a form in order to easily use it with JavaScript.
  • method is either GET or POST; these are the two ways the data can be sent to the server.
  • action is the CGI script that the form data will be sent to when submitted. You can also use the mailto: action to send the form's results to an email address, as described later in this hour.
  • enctype is the MIME type the form's data will be encoded with. This is usually not necessary; see the "[Sending Form Results by Email]" section of this hour for an example that requires it.

For example, here is a <form> tag for a form named Order. This form uses the GET method and sends its data to a CGI script called order.cgi in the same directory as the web page itself:

<form name="Order" method="GET" action="order.cgi">

For a form that will be processed entirely by JavaScript (such as a calculator or an interactive game), the method and action attributes are not needed. You can use a simple <form> tag that names the form:

<form name="calcform">

The <form> tag is followed by one or more form elements. These are the data fields in the form, such as text fields, buttons, and check boxes. In the next section, you'll learn how JavaScript assigns objects to each of the form elements.

Using the form Object with JavaScript

wax ka badal

Each form in your HTML page is represented in JavaScript by a form object, which has the same name as the NAME attribute in the <form> tag you used to define it.

Alternatively, you can use the forms array to refer to forms. This array includes an item for each form element, indexed starting with 0. For example, if the first form in a document has the name form1, you can refer to it in one of two ways:

document.form1
document.forms[0]

The form Object's Properties

wax ka badal

Along with the elements, each form object also has a list of properties, most of which are defined by the corresponding <form> tag. You can also set these from within JavaScript. They include the following:

  • action is the form's action attribute, or the program to which the form data will be submitted.
  • encoding is the MIME type of the form, specified with the enctype attribute. In most cases, this is not needed. See the "[Sending Form Results by Email]" section of this hour for an example of its use.
  • length is the number of elements in the form. You cannot change this property.
  • method is the method used to submit the form, either GET or POST. This determines the data format used to send the form result to a CGI script, and does not affect JavaScript.
  • target specifies the window in which the result of the form (from the CGI script) will be displayed. Normally, this is done in the main window, replacing the form itself, but you can use this attribute to work with pop-up windows or frames.

Submitting and Resetting Forms

wax ka badal

The form object has two methods, submit() and reset(). You can use these methods to submit the data or reset the form yourself, without requiring the user to press a button. One reason for this is to submit the form when the user clicks an image or performs another action that would not usually submit the form.

Watch Out!
If you use the submit() method to send data to a server or by email, most browsers will prompt the user to verify that he or she wants to submit the information. There's no way to do this behind the user's back.

Detecting Form Events

wax ka badal

The form object has two event handlers, onSubmit and onReset. You can specify a group of JavaScript statements or a function call for these events within the <form> tag that defines the form.

If you specify a statement or a function for the onSubmit event, the statement is called before the data is submitted to the CGI script. You can prevent the submission from happening by returning a value of false from the onSubmit event handler. If the statement returns true, the data will be submitted. In the same fashion, you can prevent a Reset button from working with an onReset event handler.

Scripting Form Elements

wax ka badal

The most important property of the form object is the elements array, which contains an object for each of the form elements. You can refer to an element by its own name or by its index in the array. For example, the following two expressions both refer to the first element in the order form, the name1 text field:

document.order.elements[0]
document.order.name1
By the Way
Both forms and elements can be referred to by their own names or as indices in the forms and elements arrays. For clarity, the examples in this hour use individual form and element names rather than array references. You'll also find it easier to use names in your own scripts.

If you do refer to forms and elements as arrays, you can use the length property to determine the number of objects in the array: document.forms.length is the number of forms in a document, and document.form1.elements.length is the number of elements in the form1 form.

You can also access form elements using the W3C DOM. In this case, you use an id attribute on the form element in the HTML document, and use the document.getElementById() method to find the object for the form. For example, this statement finds the object for the text field called firstname and stores it in the fn variable:

fn = document.getElementById("firstname");

This allows you to quickly access a form element without first finding the form object. You can assign an id to the <form> tag and find the corresponding object if you need to work with the form's properties and methods.

Did you Know?
See [Hour 13], "Using the W3C DOM," for details on the document.getElementById() method.

Text Fields

wax ka badal

Probably the most commonly used form elements are text fields. You can use them to prompt for a name, an address, or any information. With JavaScript, you can display text in the field automatically. The following is an example of a simple text field:

<input type="TEXT" name="text1" value="hello" size="30">

This defines a text field called text1. The field is given a default value of "hello" and allows up to 30 characters to be entered. JavaScript treats this field as a text object with the name text1.

Text fields are the simplest to work with in JavaScript. Each text object has the following properties:

  • name is the name given to the field. This is also used as the object name.
  • defaultValue is the default value and corresponds to the VALUE attribute. This is a read-only property.
  • value is the current value. This starts out the same as the default value, but can be changed, either by the user or by JavaScript functions.

When you work with text fields, most of the time you will use the value attribute to read the value the user has entered or to change the value. For example, the following statement changes the value of a text field called username in the order form to "John Q. User":

document.order.username.value = "John Q. User"

Text Areas

wax ka badal

Text areas are defined with their own tag, <textarea>, and are represented by the textarea object. There is one major difference between a text area and a text field: Text areas enable the user to enter more than just one line of information. Here is an example of a text area definition:

<textarea name="text1" rows="2" cols="70">
This is the content of the TEXTAREA tag.
</textarea>

This HTML defines a text area called text1, with two rows and 70 columns available for text. In JavaScript, this would be represented by a text area object called text1 under the form object.

The text between the opening and closing <textarea> tags is used as the initial value for the text area. You can include line breaks within the default value with the special character \n.

Working with Text in Forms

wax ka badal

The text and textarea objects also have a few methods you can use:

  • focus() sets the focus to the field. This positions the cursor in the field and makes it the current field.
  • blur() is the opposite; it removes the focus from the field.
  • select() selects the text in the field, just as a user can do with the mouse. All of the text is selected; there is no way to select part of the text.

You can also use event handlers to detect when the value of a text field changes. The text and textarea objects support the following event handlers:

  • The onFocus event happens when the text field gains focus.
  • The onBlur event happens when the text field loses focus.
  • The onChange event happens when the user changes the text in the field and then moves out of it.
  • The onSelect event happens when the user selects some or all of the text in the field. Unfortunately, there's no way to tell exactly which part of the text was selected. (If the text is selected with the select() method described previously, this event is not triggered.)

If used, these event handlers should be included in the <input> tag declaration. For example, the following is a text field including an onChange event that displays an alert:

<input type="TEXT" name="text1" onChange="window.alert('Changed.');">

One of the most useful types of form element is a button. Buttons use the <input> tag and can use one of three different types:

  • type=SUBMIT is a Submit button. This button causes the data in the form fields to be sent to the CGI script.
  • type=RESET is a Reset button. This button sets all the form fields back to their default value, or blank.
  • type=BUTTON is a generic button. This button performs no action on its own, but you can assign it one using a JavaScript event handler.

All three types of buttons include a name attribute to identify the button and a value attribute that indicates the text to display on the button's face. A few buttons were used in the examples in [Hour 10], "Using Windows and Frames." As another example, the following defines a Submit button with the name sub1 and the value "Click Here":

<input type="SUBMIT" name="sub1" value="Click Here">

If the user presses a Submit or a Reset button, you can detect it with the onSubmit or onReset event handlers, described earlier in this hour. For generic buttons, you can use an onClick event handler.

Check Boxes

wax ka badal

A check box is a form element that looks like a small box. Clicking on the check box switches between the checked and unchecked states, which is useful for indicating Yes or No choices in your forms. You can use the <input> tag to define a check box. Here is a simple example:

<input type="CHECKBOX" name="check1" value="Yes" checked>

Again, this gives a name to the form element. The value attribute assigns a meaning to the check box; this is a value that is returned to the server if the box is checked. The default value is "on." The checked attribute can be included to make the box checked by default.

A check box is simple: It has only two states. Nevertheless, the checkbox object in JavaScript has four different properties:

  • name is the name of the check box, and also the object name.
  • value is the "true" value for the check box—usually on. This value is used by server-side programs to indicate whether the check box was checked. In JavaScript, you should use the checked property instead.
  • defaultChecked is the default status of the check box, assigned by the checked attribute in HTML.
  • checked is the current value. This is a Boolean value: true for checked and false for unchecked.

To manipulate the check box or use its value, you use the checked property. For example, this statement turns on a check box called same in the order form:

document.order.same.checked = true;

The check box has a single method, click(). This method simulates a click on the box. It also has a single event, onClick, which occurs whenever the check box is clicked. This happens whether the box was turned on or off, so you'll need to examine the checked property to see what happened.

Radio Buttons

wax ka badal

Another element for decisions is the radio button, using the <input> tag's RADIO type. Radio buttons are also known as option buttons. These are similar to check boxes, but they exist in groups and only one button can be checked in each group. They are used for a multiple-choice or "one of many" input. Here's an example of a group of radio buttons:

<input type="RADIO" name="radio1" value="Option1" checked> Option 1
<input type="RADIO" name="radio1" value="Option2"> Option 2
<input type="RADIO" name="radio1" value="Option3"> Option 3

These statements define a group of three radio buttons. The name attribute is the same for all three (which is what makes them a group). The value attribute is the value passed to a script or a CGI program to indicate which button is selected—be sure you assign a different value to each button.

By the Way
Radio buttons are named for their similarity to the buttons on old pushbutton radios. Those buttons used a mechanical arrangement so that when you pushed one button in, the others popped out.

As for scripting, radio buttons are similar to check boxes, except that an entire group of them shares a single name and a single object. You can refer to the following properties of the radio object:

  • name is the name common to the radio buttons.
  • length is the number of radio buttons in the group.

To access the individual buttons, you treat the radio object as an array. The buttons are indexed, starting with 0. Each individual button has the following properties:

  • value is the value assigned to the button. (This is used by the server.)
  • defaultChecked indicates the value of the checked attribute and the default state of the button.
  • checked is the current state.

For example, you can check the first radio button in the radio1 group on the form1 form with this statement:

document.form1.radio1[0].checked = true;

However, if you do this, be sure you set the other values to false as needed. This is not done automatically. You can use the click() method to do both of these in one step.

Like a check box, radio buttons have a click() method and an onClick event handler. Each radio button can have a separate statement for this event.

Did you Know?
You can have more than one group of radio buttons on a page, and they will act independently. Assign a separate name attribute value to each group.
wax ka badal

A final form element is also useful for multiple-choice selections. The <select> HTML tag is used to define a selection list, or a drop-down list of text items. The following is an example of a selection list:

<select name="select1" SIZE=40>
<option value="choice1" SELECTED>This is the first choice.
<option value="choice2">This is the second choice.
<option value="choice3">This is the third choice.
</select>

Each of the <option> tags defines one of the possible choices. The value attribute is the name that is returned to the program, and the text outside the <option> tag is displayed as the text of the option.

An optional attribute to the <select> tag, multiple, can be specified to allow multiple items to be selected. Browsers usually display a single-selection <select> as a drop-down list and a multiple-selection list as a scrollable list.

The object for selection lists is the select object. The object itself has the following properties:

  • name is the name of the selection list.
  • length is the number of options in the list.
  • options is the array of options. Each selectable option has an entry in this array.
  • selectedIndex returns the index value of the currently selected item. You can use this to check the value easily. In a multiple-selection list, this indicates the first selected item.

The options array has a single property of its own, length, which indicates the number of selections. In addition, each item in the options array has the following properties:

  • index is the index into the array.
  • defaultSelected indicates the state of the selected attribute.
  • selected is the current state of the option. Setting this property to true selects the option. The user can select multiple options if the multiple attribute is included in the <select> tag.
  • name is the value of the name attribute. This is used by the server.
  • text is the text that is displayed in the option.

The select object has two methods—blur() and focus()—which perform the same purposes as the corresponding methods for text objects. The event handlers are onBlur, onFocus, and onChange, also similar to other objects.

By the Way
You can change selection lists dynamically—for example, choosing a product in one list could control which options are available in another list. You can also add and delete options from the list.

Reading the value of a selected item is a two-step process. You first use the selectedIndex property, and then use the value property to find the value of the selected choice. Here's an example:

ind = document.navform.choice.selectedIndex;
val = document.navform.choice.options[ind].value;

This uses the ind variable to store the selected index, and then assigns the val variable to the value of the selected choice. Things are a bit more complicated with a multiple selection: You have to test each option's selected attribute separately.

Displaying Data from a Form

wax ka badal

As a simple example of using forms, [Listing 11.1] shows a form with name, address, and phone number fields, as well as a JavaScript function that displays the data from the form in a pop-up window.

Listing 11.1. A Form That Displays Data in a Pop-up Window
<html>
<head>
<title>Form Example</title>
<script language="JavaScript" type="text/javascript">
function display() {
DispWin = window.open('','NewWin',
'toolbar=no,status=no,width=300,height=200')
message = "<ul><li><b>NAME: </b>" + document.form1.yourname.value;
message += "<li><b>ADDRESS: </b>" + document.form1.address.value;
message += "<li><b>PHONE: </b>" + document.form1.phone.value + "</ul>";
DispWin.document.write(message);
}
</script>
</head>
<body>
<h1>Form Example</h1>
Enter the following information. When you press the Display button,
the data you entered will be displayed in a pop-up window.
<form name="form1">
<p><b>Name:</b> <input type="TEXT" size="20" name="yourname">
</p>
<p><b>Address:</b> <input type="TEXT" size="30" name="address">
</p>
<p><b>Phone: </b> <input type="TEXT" size="15" name="phone">
</p>
<p><input type="BUTTON" value="Display" onClick="display();"></p>
</form>
</body>
</html>

Here is a breakdown of how this HTML document and script work:

  • The <script> section in the document's header defines a function called display() that opens a new window (as described in [Hour 10]) and displays the information from the form.
  • The <form> tag begins the form. Because this form is handled entirely by JavaScript, no form action or method is needed.
  • The <input> tags define the form's three fields: yourname, address, and phone. The last <input> tag defines the Display button, which is set to run the display() function.
Did you Know?
As usual, you can download the listings for this hour from this book's website.

[Figure 11.1] shows this form in action. The Display button has been pressed, and the pop-up window shows the results.

Sending Form Results by Email

wax ka badal

One easy way to use a form is to send the results by email. You can do this without using any JavaScript, although you could use JavaScript to validate the information entered (as you'll learn later in this hour).

To send a form's results by email, you use the mailto: action in the form's action attribute. [Listing 11.2] is a modified version of the name and address form from [Listing 11.1] that sends the results by email.

Listing 11.2. Sending a Form's Results by Email
<html>
<head>
<title>Email Form Example</title>
</head>
<body>
<h1>Email Form Example</h1>
Enter the following information. When you press the Submit button,
the data you entered will be sent by email.
<form name="form1" action="mailto:user@host.com"
enctype="text/plain" method="POST">
<p><b>Name:</b> <input type="TEXT" size="20" name="yourname">
</p>
<p><b>Address:</b> <input type="TEXT" size="30" name="address">
</p>
<p><b>Phone: </b> <input type="TEXT" size="15" name="phone">
</p>
<p><input type="submit" value="Submit"></p>
</form>
</body>
</html>

To use this form, change user@host.com in the action attribute of the <form> tag to your email address. Notice the enctype=text/plain attribute in the <form> tag. This ensures that the information in the email message will be in a readable plain-text format rather than encoded.

Although this provides a quick and dirty way of retrieving data from a form, the disadvantage of this technique is that it is highly browser dependent. Whether it will work for each user of your page depends on the configuration of his or her browser and email client.

Watch Out!
Because this technique does not consistently work on all browsers, I don't recommend you use it. For a more reliable way of sending form results, you can use a CGI form-to-email gateway. Several free CGI scripts and services are available. You'll find links to them on this book's website.

Try It Yourself Validating a Form

wax ka badal

One of JavaScript's most useful purposes is validating forms. This means using a script to verify that the information entered is valid—for example, that no fields are blank and that the data is in the right format.

You can use JavaScript to validate a form whether it's submitted by email or to a CGI script, or is simply used by a script. [Listing 11.3] is a version of the name and address form that includes validation.

Listing 11.3. A Form with a Validation Scrip
<html>
<head>
<title>Form Example</title>
<script language="JavaScript" type="text/javascript">
function validate() {
if (document.form1.yourname.value.length < 1) {
alert("Please enter your full name.");
return false;
}
if (document.form1.address.value.length < 3) {
alert("Please enter your address.");
return false;
}
if (document.form1.phone.value.length < 3) {
alert("Please enter your phone number.");
return false;
}
return true;
}
</script>
</head>
<body>
<h1>Form Example</h1>
<p>Enter the following information. When you press the Submit button,
the data you entered will be validated, then sent by email.</p>
<form name="form1" action="mailto:user@host.com" enctype="text/plain"
method="POST" onSubmit="return validate();">
<p><b>Name:</b> <input type="TEXT" size="20" name="yourname">
</p>
<p><b>Address:</b> <input type="TEXT" size="30" name="address">
</p>
<p><b>Phone: </b> <input type="TEXT" size="15" name="phone">
</p>
<p><input type="SUBMIT" value="Submit"></p>
</form>
</body>
</html>

This form uses a function called validate() to check the data in each of the form fields. Each if statement in this function checks a field's length. If the field is long enough to be valid, the form can be submitted; otherwise, the submission is stopped and an alert message is displayed.

By the Way
The validation in this script is basic—you could go further and ensure that the phone field contains only numbers, and the right amount of digits, by using JavaScript's string features described in [Hour 5], "Using Variables, Strings, and Arrays."

This form is set up to send its results by email, as in [Listing 11.2]. If you wish to use this feature, be sure to read the information about email forms earlier in this hour and change user@host.com to your desired email address.

The <form> tag uses an onSubmit event handler to call the validate() function. The return keyword ensures that the value returned by validate() will determine whether the form is submitted.

Did you Know?
You can also use the onChange event handler in each form field to call a validation routine. This allows the field to be validated before the Submit button is pressed.

[Figure 11.2] shows this script in action, as displayed by Firefox. The form has been filled out except for the name, and a dialog box indicates that the name needs to be entered.

During this hour, you've learned all about HTML forms and how they can be used with JavaScript. You learned about the form object and the objects for the various form elements, and used them in several example scripts.

You also learned how to submit a form by email, and how to use JavaScript to validate a form before it is submitted.

In the next hour, you'll look at CSS (Cascading Style Sheets)—a standards-compliant way to achieve just about any visual effect on a page, and the foundation for using JavaScript to change a page's appearance.

Q1
If I use JavaScript to add validation and other features to my form, can users with non-JavaScript browsers still use the form?
A1
Yes, if you're careful. Be sure to use a Submit button rather than the submit action. Also, the CGI script might receive nonvalidated data, so be sure to include the same validation in the CGI script. Non-JavaScript users will be able to use the form, but won't receive instant feedback about their errors.
Q2
Can I add new form elements on the fly or change them—for example, change a text box into a password field?
A2
Not in the traditional way described in this hour. However, you can change any aspect of a page, including adding, removing, or changing form elements, using the W3C DOM. See [Hour 13] for details.
Q3
Is there any way to create a large number of text fields without dealing with different names for all of them?
A3
Yes. If you use the same name for several elements in the form, their objects will form an array. For example, if you defined 20 text fields with the name member, you could refer to them as member[0] through member[19]. This also works with other types of form elements.


Q4
Is there a way to place the cursor on a particular field when the form is loaded, or after my validation routine displays an error message?
A4
Yes. You can use the field's focus() method to send the cursor there. To do this when the page loads, you can use the onLoad method in the <body> tag. However, there is no way to place the cursor in a particular position within the field.

Quiz Questions

wax ka badal

Test your knowledge of JavaScript and forms by answering the following questions.

1: Which of these attributes of a <form> tag determines where the data will be sent?

  1. action
  1. method
  2. name

2: Where do you place the onSubmit event handler to validate a form?

  1. In the <body> tag
  2. In the <form> tag
  3. In the <input> tag for the Submit button

3: What can JavaScript do with forms that a CGI script can't?

  1. Cause all sorts of problems
  2. Give the user instant feedback about errors
  3. Submit the data to a server

Quiz Answers

wax ka badal

1. a. The action attribute determines where the data is sent.

2. b. You place the onSubmit event handler in the <form> tag.

3. b. JavaScript can validate a form and let the user know about errors immediately, without waiting for a response from a server.

To further explore the JavaScript features you learned about in this hour, you can perform the following exercises:

  • Change the validate function in [Listing 11.3] so that after a message is displayed indicating that a field is wrong, the cursor is moved to that field. (Use the focus() method for the appropriate form element.)
  • Add a text field to the form in [Listing 11.3] for an email address. Add a feature to the validate function that verifies that the email address is at least five characters and that it contains the @ symbol.