Main Page

Getting form references

<!-- multiline textbox -->
<label for=”txtComments”>Comments:</label><br />
<textarea rows=”10” cols=”50” id=”txtComments”
name=”txtComments”></textarea><br />
<!-- submit button -->
<input type=”submit” value=”Submit Form” />
In this example, five form fields are described: a regular text box, a password text box, a combo box, a
multiline text box, and a Submit button. Note that with the exception of the Submit button, each field is
preceded by a
element. This element is used behind the scenes to logically tie a label to a par-
ticular form field. This feature is very useful for screen readers used by visually impaired users. The
attribute indicates the ID of the form field it identifies. Because of this, each form field should have
equal to the same value (
is submitted to the server;
identifies the element on the client).
Each type of form field can be manipulated using JavaScript. The
element itself can also be
controlled using JavaScript to provide further control over transmission of data.
Scripting the <form/> Element
Using JavaScript with the
element is different from using other HTML elements. You aren’t
limited to just using the core DOM methods to access forms; you can access both the
itself and the form fields in a few different ways. This section covers the basic information you need to
begin scripting forms.
Getting form references
Before scripting a form, you first must get a reference to the
element. This can be done in a
number of different ways.
First, you can use the typical method of locating an element in a DOM tree, that is, use
and pass in the form’s ID:
var oForm = document.getElementById(“form1”);
Alternately, you can use the
collection and reference the form either by its position in
collection or by its
var oForm = document.forms[0]; //get the first form
var oOtherForm = document.forms[“formZ”]; //get the form whose name is “formZ”
Any of these methods for retrieving a form reference is acceptable (they all return the same thing, after all).
Forms and Data Integrity
14_579088 ch11.qxd 3/28/05 11:40 AM Page 337

JavaScript EditorFree JavaScript Editor     Ajax Editor