Previous Page TOC Next Page See Page



- 7 -
Working with Forms


HTML provides for basic interactivity with forms. Forms enable page authors to request user input with a variety of interface tools, including text fields, checkboxes, and drop-down lists. However, the degree of interaction with the user is limited because the data from the forms must be submitted to the server for processing.

Client JavaScript extends this model to enable interactivity in forms without requiring the form's content to be sent to the server. Forms are defined in JavaScript with the Form object and each form element, such as text input fields and radio buttons, are further defined by objects. This chapter examines these objects and their properties, methods, and events. The topics to be discussed include the following:


The <FORM> Tag


Forms in HTML are defined using the <FORM> tag. Using the <FORM> tag, the global properties of a form are defined, including how the document should be processed, the name of the form, and an event handler for when a form is submitted.

The <FORM> tag takes 5 possible attributes[em]METHOD, ACTION, TARGET, NAME, and ENCTYPE—in addition to the onSubmit event handler.

The METHOD Attribute


The METHOD attribute can take two values: GET or POST. These indicate how the form data should be submitted to the server for CGI processing. The GET method attaches all the contents of the form elements to the URL specified in the ACTION attribute.

The GET Method

GET-type submissions look like:

Script_URL?element_name_1=element_value_1&element_name_2=element_value_2

The Script_URL is specified with the ACTION attribute, which is discussed in a following section. This is followed by a question mark and then name=value pairs for each form element. Each pair is separated by an ampersand.

The POST Method

Unlike the GET method, the POST method transfers the form content to the server through the standard-input, which is accessible to CGI scripts or programs.

The ACTION Attribute


The ACTION attribute is used to specify the URL of a CGI script or a LiveWire application which will process the contents of the form. ACTION URLs also can take the form mailto:email@host.name if the contents of the form are simply to be emailed to someone.

For instance, to direct the contents of the form to a CGI script called processform using the POST method, the FORM tag would look like

<FORM METHOD=POST ACTION="/cgi-bin/processform">

The TARGET Attribute


The TARGET attribute is used to indicate the window or frame where the results of processing the form contents should be displayed. Anything returned from the CGI script or LiveWire application specified in the ACTION attribute is displayed in the named frame or window.

In addition to specifying existing windows or frames, new windows can be created to display the returned content simply by specifying a new name in the TARGET attribute.

In addition, the four special window names—_top, _parent, _self, and _blank—can be used in the TARGET attribute. These are discussed in more detail in Chapter 8, "Frames and JavaScript."

The NAME Attribute


The NAME attribute enables each form to be named. This is useful in scripts in which more than one form needs to be worked with. You see how named forms are used later in this chapter.



Note:

Names of forms, like names of windows and frames, cannot contain any spaces.



The ENCTYPE Attribute


The ENCTYPE attribute specifies the MIME type of the data being sent from the form to the script on the server. The default mime type is application/x-www-form-urlencoded.

The form Object


Each form in an HTML document is defined by its own object in JavaScript. As you learned in Chapter 5 when you looked at the Navigator Object Tree, the form object is a property of the document object.

The forms Array


All the forms in an HTML document are stored in array called forms, so it's possible to access a specific form, and its properties or methods, using an index number. Indexes for each form are numbered sequentially as they are defined in the HTML document and start at zero—the default initial index for all JavaScript arrays. For instance, you can refer to

document.forms[index].propertyName

or

document.forms[index].methodName()

At the same time, forms can be referred to by the name specified in the NAME attribute of the <FORM> tag. For instance, document.formName.propertyName, refers to a property of the form with the name formName.

Properties of the form Object


The form object has six properties—action, elements, encoding, length, method, and target. In addition, objects for each form element are properties of the form object.

The action Property

The action property is a string that reflects the ACTION attribute of the <FORM> tag. The action property can be dynamically changed at any time by assigning a new string to the property. This effectively overrides any ACTION value specified in the <FORM> tag.

For instance, if the ACTION attribute of a form named formName has been defined as Script_URL in the <FORM> tag then

document.formName.action = "New_Script_URL";

would change the value to New_Script_URL and any subsequent attempt to submit the form's contents would direct the submission to New_Script_URL instead of Script_URL.

The elements Array

The elements array is an array of objects for each element in the form. The elements appear in the array in the order in which they appear in the HTML source code.

The elements array can be used to reference specific form elements. For instance,

document.formName.elements[0]

refers to the first element in the form named formName, and

document.forms[1].elements[2]

refers to the third element in the second form in a document.

Like the forms array, an alternate method of referring to form elements is by their names. As you will see later in this chapter when individual form elements are discussed, these elements can have names.

For instance, you could refer to a text field named fieldName in a form named formName as

document.formName.fieldName

The length of the elements array is specified by the length property:

document.formName.elements.length

The encoding Property

The encoding property is a string that reflects the value of the ENCTYPE attribute in the <FORM> tag. It specifies the MIME type of the data being submitted to the server for processing.

Like the action property, a new value can be assigned to the encoding property at any time, effectively overriding the value specified in the ENCTYPE attribute.

The length Property

Like the length property of the elements array, the number of elements in a form is also reflected in the length property of the form object. Just as

document.formName.elements.length

reflects the number of elements in a form, so does

document.formName.length

The method Property

The method property is a string that reflects the value of the METHOD attribute of the <FORM> tag. Its value should be either get or post.

Like the action and encoding properties, a new value can be assigned to the method property, effectively overriding the value specified in the METHOD attribute.

The target Property

The target property is a string that reflects the value of the TARGET attribute of the <FORM> tag. Its value is the name of the frame or window which that receives the result of submitting the form.

Again, the target property can be assigned a new value, overriding the original value in the <FORM> tag. The value assigned to the target property can't be an expression or variable.

Methods of the form Object


The form object has one method—the submit() method.

The submit() Method

The submit() method submits the form as if the user had clicked on the submit button. The submit() also triggers the onSubmit event handler for the given form.



Note:

Event methods such as submit() trigger their corresponding event handlers. It's important to be aware of this and ensure that you avoid circular loops in which event handlers call their corresponding event methods, in turn triggering the event hander again.



Event Handlers of the form Object


The form object has one event handler—the onSubmit event handler.

The onSubmit Event Handler

The onSubmit event handler is specified in the <FORM> tag:

<FORM METHOD="method" ACTION="action" onSubmit="JavaScript_Code">

The code executed by the onSubmit event handler can be used to prevent the form from being submitted. If the code uses a return statement to return a value of false, then the form isn't submitted. Otherwise the form is submitted.

Field-Based Objects


HTML forms can contain 7 different types of input fields: text fields, textarea fields, radio buttons, checkbox buttons, hidden fields, password fields, and select menus.

Each of these fields is reflected by an object that is also a property of the form object.

The <INPUT> tag is used to define many of these fields in a form. The <INPUT> tag takes four attributes: TYPE, NAME, VALUE, and SIZE. The <INPUT> tag is used to define five of the input fields—text fields, radio buttons, checkbox buttons, hidden fields, and password fields—as well as the button elements discussed later in this chapter.

The TYPE attribute specifies the type of form element being defined with the <INPUT> tag. It takes the following possible values: text, radio, checkbox, hidden, password, button, reset or submit.

The NAME attribute is a string specifying the name of the field, and the VALUE attribute is a string specifying the initial value of a text field or the name of a button or checkbox.

The SIZE attribute specifies the number of characters a text field can display before it has to scroll the text in the field. The value of SIZE is an integer.

The text Object


The text object reflects text fields in forms. Text fields are single-line fields where the user can enter text in the form. They are defined using the <INPUT> tag. For instance,

<INPUT TYPE="text" NAME="fieldName" VALUE="initialValue" SIZE="size">

defines a text field with the name fieldName, and initial value of initialValue and a size of size characters.

The text object has three properties, three methods, and four event handlers.

The defaultValue Property

The defaultValue property reflects the initial value of a text field as defined by the VALUE attribute of the INPUT tag. It is a string.

The value of defaultValue can be changed but doesn't cause the displayed value of the field to be updated. Rather, next time the defaultValue property is evaluated it returns the new value. For instance, the following code segment changes the defaultValue of the text field named firstName in the form named testForm:

document.testForm.firstName.defaultValue = "A New Value";

Subsequent references to document.testForm.firstName.defaultValue return "A New Value".

The name Property

The name property is a string containing the value of the NAME attribute in the INPUT tag. The name property can be changed to override the value in the NAME attribute.

The following for loop searches through all the elements of a form named thisForm and when it finds a field named testField, it changes the name to newTestField:

for (i = 0; i < document.thisForm.elements.length; i++) {
   if (document.thisForm.elements[i].name == "testField")
   document.thisForm.elements[i].name = "newTestField";
}

The value Property

The value property is a string value reflecting the current value in the text field. Changing the value of the value property causes the actual text displayed in the text field to be updated to the new value of the property.

The focus() Method

The focus() method causes input focus to be directed to the text object. This then enables the user to enter text into the field or the data in the field to be changed by the script.

See the following example:

<FORM METHOD=POST ACTION="SomeURL" NAME="testForm"  

[ic:ccc]onSubmit="if (document.testForm.nameField.value == "") { alert ("Please enter a name"); document.testForm.nameField.focus(); return false; }"> <INPUT TYPE="text" NAME="nameField" VALUE="" SIZE=30> <INPUT TYPE="submit"> </FORM>

The focus() method is used in the onSubmit event handler. If the field nameField is blank, focus is returned to the field and the submit event is canceled by returning a false value.

The blur() Method

Focus is removed from a text field using the blur() method.

For instance, in the following code segment, the field displayField is used by the script to display output but should not be alterable by the user. The blur() method in the onFocus event handler ensures that focus can never be given to the field:

<INPUT TYPE="text" NAME="displayField" VALUE="Initial Value"  onFocus="this.blur()">

Notice the use of the this keyword to refer to the current text object.

The select() Method

The select() method is used to select and highlight the content of the text field. This does not, by default, force input focus into the field, however.

The following code segment gives input focus to the field nameField in the form testForm and then highlights the text in the field.

document.testForm.nameField.focus();
document.testForm.nameField.select();

Event Handlers of the text Object

The text object has four event handlers: onFocus, onBlur, onChange, and onSelect.

onFocus and onBlur specify JavaScript code to execute when input focus is given to, or removed from, the text field. onChange is triggered when the user changes the value of a text field and then removes focus from the field. The onSelect event handler specifies actions to occur when the user selects (or highlights) some or all of the text in the field.

The textarea Object


A textarea in a form is similar to a text field in that it enables the user to enter text. Unlike the text field, the textarea field supports multi-line text entry.

The textarea field is defined in a form using the <TEXTAREA> tag. The <TEXTAREA> tag takes four attributes: NAME, ROWS, COLS, and WRAP.

NAME is a string specifying the name of the text field. ROWS and COLS are integers defining the size of the viewable area of the textarea field in characters. Scrollbars enable text blocks larger than the field to be entered and viewed.

The WRAP attribute specifies how to handle text wrapping when the user enters text into the field. It takes three possible values: off, virtual, and physical. With WRAP set to off, no text wrapping occurs—the user must hit return to wrap to the next line. The virtual value causes text to be wrapped in the display but the value sent to the server for processing doesn't include the line breaks generated by line wrapping. The physical value causes text wrapping to be displayed and the resulting line breaks to be sent to the server when the form is submitted.

Initial text to be displayed in the textarea field is contained between the <TEXTAREA> and </TEXTAREA> tags.

For instance,

<TEXTAREA NAME="testField" ROWS=15 COLS=40 WRAP=physical> Initial Text </TEXTAREA>

Defines a 40 column by 15 row textrea field with physical wrapping named testField and an initial value of "Initial Text".

The textarea object has three properties, three methods, and four event handlers.

Figure 7.1. The textarea field is a multi-line text entry field that can contain an initial value.

The defaultValue Property

The defaultValue property reflects the initial value of a textarea field as defined by the text between the <TEXTAREA> and </TEXTAREA> tags.

The value of defaultValue can be changed but doesn't cause the displayed value of the field to be updated. Rather, next time the defaultValue property is evaluated it returns the new value.

The name Property

The name property is a string containing the value of the NAME attribute in the TEXTAREA tag. The name property can be changed to override the value in the NAME attribute.

The value Property

The value property is a string value reflecting the current value in the textarea field. Changing the value of the value property causes the actual text displayed in the textarea field to be updated to the new value of the property.

The focus() Method

The focus() method causes focus to be directed to the textarea object. This then enables the user to enter text into the field or the data in the field to be changed by the script.

The blur() Method

Focus is removed from a textarea field using the blur() method.

The select() Method

The select() method is used to select and highlight the content of the text field. This does not, by default, force input focus into the field, however.

Event Handlers of the textarea Object

The textarea object has four event handlers: onFocus, onBlur, onChange, and onSelect.

onFocus and onBlur specify JavaScript code to execute when input focus is given to, or removed from, the textarea field. onChange is triggered when the user changes the value of a textarea field and then removes focus from the field. The onSelect event handler specifies actions to occur when the user selects (or highlights) some or all of the text in the field.

The radio Object


Radio buttons are a set of clickable buttons on an HTML form in which only one button can be selected at any one time.

They are defined by multiple <INPUT> tags all with TYPE set to radio and the same NAME. The VALUE attribute of each <INPUT> tag specifies the value sent to the server when the form is submitted. A special attribute, CHECKED, enables the initial selection to be specified.

The text to be displayed next to each radio button is placed outside the <INPUT> tags.

For instance, the HTML code

<INPUT TYPE=radio NAME=testRadio VALUE="One">Choice One<BR>
<INPUT TYPE=radio NAME=testRadio VALUE="Two" CHECKED>Choice Two<BR>
<INPUT TYPE=radio NAME=testRadio VALUE="Three">Choice Three

produces results similar to those shown in Figure 7.2.

Figure 7.2. Radio buttons enable users to select one of many options.

Individual radio buttons within the set of radio buttons are referenced by index numbers. For instance, the third of the preceding choices above would be referred to by document.formName.testRadio[2] and its properties would be referred to as document.formName.testRadio[2].propertyName.

Radio buttons have five properties, one method, and one event handler.

The checked Property

The checked property is a Boolean indicating if a given radio button is checked or unchecked. It evaluates to true if the button is checked. The value of checked can be set at any time to force a new button to be selected.

For instance, in the preceding radio button example, the initial value of document.formName.testRadio[1].checked is true and both document.formName.testRadio[0].checked and document.formName.testRadio[2].checked are false. By setting

document.formName.testRadio[2].checked = true;

the third button becomes selected and the second button is deselected.

The defaultChecked Property

The defaultChecked property reflects whether the CHECKED attribute appears in the <INPUT> tag for a given button. It is a Boolean value that can be overridden by setting the value of the defaultChecked property.

The length Property

The length property is an integer value indicating the number of buttons in a radio button object. Because it's not specific to a particular button in a group, the use of an index isn't needed. For instance, in the preceding example,

document.formName.testRadio.length

has a value of 3.

The name Property

The value of NAME attribute in the <INPUT> tag is reflected in the name property. The value can be changed by assigning a new value to name, overriding the value in the NAME attribute.

The value Property

The value property reflects the value of the VALUE attribute for a particular button. This should not be confused with the selection state of a specific button or the text displayed to the user.

The value of the value property can be changed to override the VALUE attribute.

The click() Method

The click() method is used to cause a radio button to be selected. The click() method simulates a mouse click on the button. Similar results can be achieved as setting the checked property manually.

For instance, in the example above, where the selected radio button was changed to the third button, it is also possible to use

document.formName.testRadio[2].click()

The onClick Event Handler

The onClick event handler specifies actions to take when a specific button is selected. Each button in a radio object can have a different onClick event handler:

<INPUT TYPE=radio NAME=testRadio VALUE="One" onClick="alert('one')">Choice One<BR>
<INPUT TYPE=radio NAME=testRadio VALUE="Two" CHECKED onClick="alert('two')">Choice Two<BR>
<INPUT TYPE=radio NAME=testRadio VALUE="Three" onClick="alert('three')">Choice Three

The checkbox Object


Checkboxes are on-off toggle switches. Unlike radio buttons, which function in groups, checkboxes are individual toggle switches.

The <INPUT> tag is used to create a checkbox. The TYPE attribute needs to be set to checkbox. The VALUE attribute is used to specify the value sent to the server when the form is submitted. The CHECKED attribute can be used to cause the checkbox to be checked when it first displays.

Like radio buttons, the text to be displayed is placed outside the <INPUT> tag:

<INPUT TYPE="checkbox" NAME="testCheck" VALUE="testValue" CHECKED>Checkbox

Figure 7.3. Checkboxes are toggle switches that can be selected or deselected by the user.

The checkbox object reflects checkboxes from HTML forms. It has four properties and, like radio buttons, one method and one event handler.

The checked Property

The checked property is a Boolean indicating if a given checkbox is checked or unchecked. It evaluates to true if the button is checked. The value of checked can be set at any time to force a new button to be selected.

For instance, in the preceding checkbox button example, the initial value of document.formName.testCheck.checked is true. By setting

document.formName.testCheck.checked = false;

the display is updated so that the checkbox is unchecked.

The defaultChecked Property

The defaultChecked property reflects whether the CHECKED attribute appears in the <INPUT> tag for the checkbox. It is a Boolean value that can be overridden by setting the value of the defaultChecked property.

The name Property

The value of NAME attribute in the <INPUT> tag is reflected in the name property. The value can be changed by assigning a new value to name, overriding the value in the NAME attribute.

The value Property

The value property reflects the value of the VALUE attribute for a particular button. This should not be confused with the selection state of a specific button or the text displayed to the user.

The value of the value property can be changed to override the VALUE attribute.

The click() Method

The click() method is used to cause a checkbox to be selected. The click() method simulates a mouse click on the button. Similar results can be achieved by setting the checked property manually.

For instance, in the preceding example where the box was checked using the checked property, it is also possible to use

document.formName.testCheck.click()

The onClick Event Handler

The onClick event handler specifies action to take when a specific button is selected.

The hidden Object


hidden objects are text fields that aren't displayed in forms. They can be used to pass values to a CGI script which aren't intended for display to the user.

Hidden fields are defined using the <INPUT> tag with a TYPE attribute set to hidden. The NAME and VALUE attributes can be used.

Properties of the hidden Object

The hidden object has two properties that function like the corresponding ones in the text object: name and value. Both are string values reflecting the corresponding attributes from the <INPUT> tag. They can be assigned new values to override the values in the <INPUT> tag.

There are no methods or event handlers for the hidden object.

The password Object


Password fields are special cases of the text field that display each character entered as an asterix (*).

The password object is defined using the <INPUT> tag with the TYPE attribute set to password. Like a text field, it can take the NAME, VALUE and SIZE attributes.

There are three properties and methods associated with the password object. The password object has no event handlers.

The defaultValue Property

The defaultValue property of the password object is somewhat different than the corresponding property of the text object. Rather than taking on the initial value of the VALUE attribute, for security reasons, the defaultValue property is set to the null value.

As with the text object, you can change the value of the defaultValue property, overriding it's initial value. When this is done, defaultValue evaluates to its new value rather than the null value.

The name Property

As with the text object, the name property is a string containing the value of the NAME attribute in the INPUT tag. The name property can be changed to override the value in the NAME attribute.

The Value Property

Like the defaultValue property, the value property functions differently than the text object's value property.

The initial value of the value property is the value set in the VALUE attribute of the <INPUT> tag. Scripts can change the value of the property by assigning new string values to it. If this is done, evaluating the value property subsequently returns the new value.

However, if the user changes the content of the password field in the form, then evaluating the value property returns the null value for security reasons.

The focus() Method

The focus() method causes focus to be directed to the password object. This then enables the user to enter text into the field or the data in the field to be changed by the script.

The blur() Method

Focus is removed from a password field using the blur() method.

The select() Method

The select() method is used to select and highlight the content of the password field. This does not, by default, force input focus into the field, however.

The select Object


The select object is different from the other form fields you have so far seen. The select object takes the shape of drop-down or scrolling menus in a form.

In the form of a drop-down menu, a single item can be selected. A scrolling list can be used to select one or more options.

Select menus are built using two tags: <SELECT> and <OPTION>.

The <SELECT> tag defines the overall menu structure and properties. It takes three attributes: NAME, SIZE, and MULTIPLE.

NAME takes a string value that specifies the name of the selection object. SIZE is an integer that indicates the number of visible items at one time. If this value is greater than one, then the list is a scrolling menu, otherwise it's a drop-down menu. MULTIPLE is used to indicate if the user should be able to select more than one item on the list. The use of the MULTIPLE attribute forces the list to be a scrolling menu even if the SIZE attribute is set to one.

For instance, the HTML code

<SELECT NAME="testSelect" SIZE=1>
Select Definition
</SELECT>

defines a drop-down menu while

<SELECT NAME="testSelect2" SIZE=4 MULTIPLE>
Select Definition
</SELECT>

defines a scrolling list with four visible items in which the user can choose more than one option.

The content of the list itself is defined using the <OPTION> tag. This tag takes two attributes: VALUE—a string specifying the value to send to the server if the option is selected when the form is submitted to the server, and SELECTED, which indicates that the option should be selected by default.

Using the <OPTION> tag, the two examples above could be extended to become

<SELECT NAME="testSelect" SIZE=1>
<OPTION VALUE="one" SELECTED>One
<OPTION VALUE="two">Two
<OPTION VALUE="three">Three
</SELECT>

and

<SELECT NAME="testSelect2" SIZE=4 MULTIPLE>
<OPTION VALUE="a">A
<OPTION VALUE="b" SELECTED>B
<OPTION VALUE="c">C
<OPTION VALUE="d" SELECTED>D
<OPTION VALUE="e">E
</SELECT>

Figure 7.4. Drop down menus and scrolling menus with multiple selections are made possible with the select object.

The select object has four properties, two methods, and three event handlers. One of the properties of the select object, the options array, provides access to each of the options in the select list. The options array, itself, has eight properties.

Properties of the select Object

In addition to the options array, the select object has three other properties: length, name, and selectedIndex.

The length property indicates the number of options in the select object. The name property is a string reflecting the NAME attribute of the <SELECT> tag. The name of the object can be changed by assigning a new value to the name property.

The selectedIndex property is an integer reflecting the index (in the options array) of currently selected options. It can be set to a new value which will dynamically update the menu's display.

However, the selectedIndex property is less useful with lists that have the MULTIPLE attribute. In these cases, the selectedIndex property evaluates to the index of the first selected option. If a new value is assigned to the property, then all selected options are cleared and the one new option is selected.

The options Array

The options array reflects the options in the select list in the order in which they are defined in the HTML source code. The options array itself has eight properties: defaultSelected, index, length, name, selected, selectedIndex, text, and value.

The length property is an integer reflecting the number of options in the select list—it is the same value as the length property of the select object.

The defaultSelected property is a Boolean value that indicates if the SELECTED attribute is used in the given option's <OPTION> tag. The value of the defaultSelected property can be changed, effectively overriding the SELECTED attribute. Changing the defaultSelected property doesn't cause the select list's appearance to be updated.

The selected property is a Boolean value reflecting the current selection state of any single option—in lists with or without the MUTLIPLE attribute set. Changing the value of the selected property dynamically changes the select list's display to reflect the new values. The selectedIndex property functions in the same way as the selectedIndex property of the select object. Because selectedIndex is not unique for any particular option, it isn't necessary to specify an index when referring to the property:

selectListName.options.selectedIndex

The name property is a string reflecting the name of the select options. Like selectedIndex, it doesn't refer to a specific option and can be referred to without an index number: selectListName.options.name.

The text property contains a string reflecting the text displayed in the select list for a given option. Similarly, the value property reflects the value of the VALUE attribute of the <OPTION> tag. Both values can be changed, effectively overriding their original values.

The index property is an integer reflecting the index of the option in question.

Dynamically Updating Select Lists

With the release of Navigator 3, it's now possible to dynamically modify the options in a select list.

By changing the value of the text property and the value property of an option, its value and the text displayed in the menu is dynamically updated to reflect the new values. In Navigator 2, changes to the text property were not reflected in the displayed menu, which retained its original appearance regardless of the value of the text property.

For instance, if you have a select list in the form formName defined as the following

<SELECT NAME="testSelect2" SIZE=4 MULTIPLE>
<OPTION VALUE="a">A
<OPTION VALUE="b" SELECTED>B
<OPTION VALUE="c">C
<OPTION VALUE="d" SELECTED>D
<OPTION VALUE="e">E
</SELECT>

then the displayed text of the third option (and the value returned to the server) can be changed:

document.formName.testSelect.options[2].text = "F";
document.formName.testSelect.options[2].value = "f";

Figure 7.5. In Navigator 3 text displayed in select lists can be dynamically changed.

Methods and Event Handlers of the select Object

The select object has two methods: blur() and focus(). Like these methods in other objects, the blur() method removes input focus from the select list and the focus() method gives input focus to the list.

Corresponding to the focus() and blur() methods are the onFocus and onBlur event handlers, which are used in the <SELECT> tag to specify code to be executed when focus is given or removed from the select list.

A third event handler, onChange, is triggered when the currently selected option or options change. The onChange event handler should be placed in the <SELECT> tag:

<SELECT NAME="selectName" SIZE=size onChange="JavaScript Code">

Button-Based Objects


HTML forms can contain three types of buttons: reset buttons, submit buttons, and generic buttons.

Reset buttons and submit buttons have specific purposes—reset buttons clear the contents of form fields to their default values and submit buttons submit the forms to the URL specified in the ACTION attribute of the <FORM> tag. Generic buttons, on the other hand, have no specific function attached to them.

All three types of buttons have JavaScript objects associated with them.

Generic Buttons


Generic buttons are defined in HTML using the <INPUT> tag with the TYPE attribute set to button. The <INPUT> tag also can take a NAME and VALUE attribute. The VALUE attribute is displayed as the text of the button in the form.

Buttons are reflected into JavaScript through the button object. The button object has two properties—name and value—that reflect the corresponding attributes from the <INPUT> tag. These properties can be changed to override their original values. Changing the value property, however, doesn't change the text that appears in the button.

The button object also has a click() method that simulates a user clicking on the button, and an onClick event handler, which specifies code to execute when the button is clicked on.

The reset Object


Reset buttons are defined using the <INPUT> tag with the TYPE attribute set to reset. NAME and VALUE attributes also can be used. The value of the VALUE attribute is displayed as the text of the button in the form.

The reset object has two properties: name and value, which can reflect the NAME and VALUE attributes in the <INPUT> tag. These properties can be changed to override their original values, but changing the value doesn't change the text displayed in the button.

Like the generic button object, the reset object has a click() method and an onClick event handler.

The submit Object


Like the generic and reset buttons, the submit button is defined with the <INPUT> tag, except that its TYPE attribute is set to submit. NAME and VALUE attributes can be used and the value of the VALUE attribute is displayed as the text of the button in the form.

The submit object has the same properties, methods, and event handlers as the reset and button objects: name and value properties, the click() method, and the onClick event handler.

Form Validation


One of the strengths of being able to work with forms in JavaScript is that it is possible to perform form validation before sending the form to the server.

With traditional CGI processing of forms, it is necessary to send a form to the server to determine if it has been correctly, and completely, filled out. If the users has incorrectly filled out the form or not provided required data then the new form has to be returned to the user requesting the corrected or additional data.

With JavaScript these extra transactions with the server can be avoided.

By way of example, the following shows form validation on a simple comments form:

<FORM METHOD=POST ACTION="/cgi-bin/comment" NAME="commentForm"  

[ic:ccc]onSubmit="if (this.name.value == "") { alert("Please enter your name."); return false; } else if (this.email.value == "") alert("Please enter your e-mail address."); return false; }"> NAME: <INPUT TYPE="text" NAME="name" SIZE=30><BR> E-MAIL ADDRESS: <INPUT TYPE="text" NAME="email" SIZE=30><BR> COMMENTS:<BR> <TEXTAREA ROWS=15 COLS=30 NAME="comments"> Enter Your Comments Here </TEXTAREA>

Figure 7.6. JavaScript can be used to validate forms like this comment form.

This form is submitted by the post method to the script /cgi-bin/comment. The form has three fields: two text fields and one textarea field.

The validation of the form takes place in the onSubmit event handler before the data is submitted to the server. Two checks are made on the form's fields. First the name field is checked to see if it is blank. If it is, the user is asked for their name and a false value is returned to prevent submission of the form.

Next, the email field is checked to see if it blank. Again, if it is, the user is alerted and a false value is returned.

Using methods of the string object, it's possible to perform more sophisticated validation on the email field, such as checking if the email address contains an @ symbol:

<FORM METHOD=POST ACTION="/cgi-bin/comment" NAME="commentForm"  

[ic:ccc]onSubmit="if (this.name.value == "") { alert("Please enter your name."); return false; } else if (this.email.value == "") { alert("Please enter your e-mail address."); return false; } else if (this.email.value.indexOf('@',0) < 0) { alert("Please enter a valid e-mail address."); return false; }"> NAME: <INPUT TYPE="text" NAME="name" SIZE=30><BR> E-MAIL ADDRESS: <INPUT TYPE="text" NAME="email" SIZE=30><BR> COMMENTS:<BR> <TEXTAREA ROWS=15 COLS=30 NAME="comments"> Enter Your Comments Here </TEXTAREA>

By using the indexOf() method of the string object, it's possible to confirm if the e-mail address has an @ symbol in it.

Summary


HTML forms provide a basic level of interactivity with Web pages. However, all this interactivity has traditionally relied on the server for processing and reacting to user input.

JavaScript makes it possible to add dynamic, client-side interactivity to HTML forms. With JavaScript, you can now react to user input, generate content for form fields, and react to user mouse-clicks in forms. Because there are so many properties, methods and event handlers, Table 7.1 outlines the properties, methods and event handlers of the various form element objects.

Table 7.1. Form element objects and their properties, methods and event handlers


Object Properties Methods Event Handlers
button name click() onClick()

value

checkbox checked click() onClick

defaultChecked


name


value

hidden name


value

password defaultValue focus()

name blur()

value

radio checked click() onClick

defaultChecked


length


name


value

reset name click() onClick

value

select length blur() onBlur

name focus() onFocus

selectedIndex
onChange

options (array)


defaultSelected


index


length


name


selected


selectedIndex


text


- value

submit name click() onClick

value

text defaultValue blur() onBlur

name focus() onFocus

value select() onSelect



onChange
textarea defaultValue blur() onBlur

name focus() onFocus

value select() onSelect



onChange

In the next chapter, frames, which allow windows to be divided into separate sections, each displaying different HTML documents, are examined. JavaScript objects and properties for working with frames will be discussed as well.

Previous Page Page Top TOC Next Page See Page