| home / programming / professional / chap6/ 1 | [previous] [next] |
|
|
The document.forms[] array object holds references to all the <form> elements in the page. To access a single form, you need to specify it in one of two ways:
By giving the index number of the form. The first form in the page has index 0, the second form index 1, and so on.
By giving the name of the form as specified in the name attribute. XHTML 1.0 Strict deprecates the name attribute of the <form> (though not of its contained elements). Instead the id attribute should be used, but older browsers can't handle this. When creating cross-browser sites, it's best to use the name attribute nonetheless.
For example, suppose you have two forms:
<form name="firstform">
<input name="yourname" />
</form>
<form name="secondform">
<input name="nickname" />
</form>
You can access the first form in two ways:
document.forms[0]
document.forms['firstform']
Similarly, these two DOM references access the second form:
document.forms[1]
document.forms['secondform']
You can even leave out the forms[] array entirely: document.firstform is a correct DOM reference and all browsers will access the form. The disadvantage is that your scripts become harder to read, which may be a problem when they need to be updated. It's better to fully write document.forms['firstform'].
IE even understands the call firstform, without any reference to the document. However, as we saw before, other browsers may have trouble with this syntax.
Here are some of the properties and methods of individual form objects.
| Property |
Read/write |
Description |
| action |
read/write |
Accesses the action attribute of the form. |
| length |
read-only |
Gives the number of elements in the form. |
| method |
read/write |
Accesses the method attribute of the form. |
| name |
read-only |
Accesses the name attribute of the form. |
| target |
read/write |
Accesses the target attribute of the form. |
| Method |
Description |
| reset() |
Resets all elements of the form to their default values. |
| submit() |
Submits the form . If you use this method, any onsubmit event handler is ignored. |
For example, these properties and methods can be used to POST a form's data to script2.pl, like this:
document.forms['firstform'].method = 'POST';
document.forms['firstform'].action = 'script2.pl'
document.forms['firstform'].submit()
| home / programming / professional / chap6/ 1 | [previous] [next] |
Created: March 11, 2003
Revised: March 11, 2003
URL: http://webreference.com/programming/professional/chap6/1