Java Reference
In-Depth Information
Next you define the for loop:
for (var formIndex = 0; formIndex < numberForms; formIndex++) {
alert(document.forms[formIndex].name);
}
Remember that because the indexes for arrays start at 0 , your loop needs to go from an index of 0 to
an index of numberForms - 1 . You enable this by initializing the index variable to 0 , and setting the
condition of the for loop to index < numberForms .
Within the for loop's code, you pass the index of the form you want (that is, index ) to document
.forms[] , which gives you the Form object at that index in the forms collection. To access the Form
object's name property, you put a dot at the end of the name of the property, name .
traditional form objeCt properties and methods
The HTML form controls commonly found in forms, which you look at in more detail shortly,
also have corresponding objects. One way to access these is through the elements property of the
Form object, another collection. The elements collection contains all the objects corresponding
to the HTML interaction elements within the form, with the exception of the little‐used
<input type="image"/> element. As you see later, this property is very useful for looping through
each of the elements in a form. For example, you can loop through each element to check that it
contains valid data prior to submitting a form.
Being a collection, the elements property of the Form object has the length property, which tells
you how many elements are in the form. The Form object also has the length property, which also
gives you the number of elements in the form. Which of these you use is up to you because both do
the same job, although writing myForm.length is shorter, and therefore quicker to type and less
lengthy to look at in code, than myForm.elements.length .
When you submit data from a form to a server, you normally use the Submit button, which you will come
to shortly. However, the Form object also has the submit() method, which does nearly the same thing.
Note The submit() method submits the form, but it does not fire the
submit event of the Form object; thus, submit event listeners are not called
when submitting the form with submit() .
Recall that in Chapter 10 you learned that you can affect whether the normal course of events
continues or is canceled. You saw, for example, that calling preventDefault() in a hyperlink's
click event handler causes the link's navigation to be canceled. Well, the same principle applies
to the Form object's submit event, which fires when the user submits the form. By calling
preventDefault() , the submission is canceled. This makes the submit event handler's code a great
place to do form validation—that is, to check that what the user has entered into the form is valid.
For example, if you ask for the users' ages and they enter mind your own business , you can spot
that this is text rather than a valid number and stop them from continuing.
 
Search WWH ::




Custom Search