Accessing forms and form elements in JavaScript can be accomplished several different ways. As you’ve seen from previous examples, paths to forms and form elements can be followed by the name assigned them via the html name attribute.
However, the generic array notation reference, when used in conjunction with loops, provides a convenient, easy reference to form element objects as well as a more efficient decision making control structure. Lets review: A form can be referenced by its order within the document’s flow, and form elements by their order within a the flow of a single set of opening and closing form tags. Say there are two forms on the page, the first form containing one element:
<form name=”formOne”>
<input type=”text” name=”elementOne”>
</form>
Take a look at three different ways to code the path to the first form element in the first form on a page.
document.formOne.elementOne
document.forms[0].elements[0]
document.forms[”formOne”].elements[”elementOne”]
For standards compliant browsers using the HTML attribute ID, there is yet another path:
<input type=”text” id=”elementOne”>
document.getElementById(”elementOne”)
Since CGI scripts require name/value pairs (not ID/value pairs) from forms, and for the sake of code compatibility between the painfully uneven support amongst varying browsers, these tutorials do not use the latter convention when dealing with forms and form elements.
As you can see, just as different forms on a single page can be referenced as part of the forms array, form elements can be referenced as part of the elements array. When it comes to providing easy access to form elements, array notation with numbers as element indices is the most efficient and simple reference convention.
This technique is applied most practically when performing form validation. Looping through elements allows for easy checks of empty values, names, element types and other properties and values specific to element types. The following example will loop through each element of the form, checking various properties and values. Here is the HTML form:
<form>
<input type=”text” size=”15″ value=”Hello World” name=”elmOne”>
<input type=”checkbox” name=”elmTwo” checked>
<textarea name=”elmThree”>Small textarea</textarea>
<select name=”elmFour”>
<option selected> Yellow
<option> Green
</select>
<input type=”button” onclick=”elmName()” name=”elmFive” value=”Display Names”>
<input type=”button” onclick=”elmLoop()” name=”elmSix” value=”Display Properties and Values”>
</form>