Java Reference
In-Depth Information
Accessing Form Elements
The legacy DOM had a useful method called document.forms that returns an HTML
collection of all the forms in the document in the order that they appear in the markup.
Even though there is only one form in our example, a collection will still be returned, so
we have to use index notation to return the first (and only) form object, like so:
var form = document.forms[0];
This is the equivalent of using the following method that we learned in chapter 6 :
form = document.getElementsByTagname('form')[0]
Instead of using a numerical index, we can use the name attribute to identify a form:
var form =;
Be careful referencing elements in this way, however. If the form had the same name as any
properties or methods of the document.forms object, such as " submit " for example,
that property or method would be referenced instead of the form element. To avoid this,
the square bracket notation can be used (this is also useful if the form's name attribute con-
tains any invalid characters, such as spaces or dashes):
var form = document.forms['search'];
A form object also has a method called elements that returns an HTML collection of all
the elements contained in the form. In this case the form contains two controls: an input
element and a button element:
var input = form.elements[0];
var button = form.elements[1];
We can also access the form controls using their name attributes as if it was a property of
the form object. So for example, the input field has a name attribute of searchBox and
can be accessed using this code:
var input = form.searchBox
Search WWH ::

Custom Search