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” />
</form>
</body>
</html>
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
<label/>
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
for
attribute indicates the ID of the form field it identifies. Because of this, each form field should have
name
and
id
equal to the same value (
name
is submitted to the server;
id
identifies the element on the client).
Each type of form field can be manipulated using JavaScript. The
<form/>
element itself can also be
controlled using JavaScript to provide further control over transmission of data.
Scripting the <form/> Element
Using JavaScript with the
<form/>
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
<form/>
element
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
<form/>
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
getElementById()
and pass in the form’s ID:
var oForm = document.getElementById(“form1”);
Alternately, you can use the
document
’s
forms
collection and reference the form either by its position in
the
forms
collection or by its
name
attribute:
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).
337
Forms and Data Integrity
14_579088 ch11.qxd 3/28/05 11:40 AM Page 337


JavaScript EditorFree JavaScript Editor     Ajax Editor


©