Java Reference
In-Depth Information
The forms Collection
trY it out
In this Try It Out, you'll use the
forms
collection to access each of three
Form
objects and show the
value of their
name
properties in a message box. Open your text editor and type the following:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Chapter 11: Example 1</title>
</head>
<body>
<form action="" name="form1">
<p>
This is inside form1.
</p>
</form>
<form action="" name="form2">
<p>
This is inside form2
</p>
</form>
<form action="" name="form3">
<p>
This is inside form3
</p>
</form>
<script>
var numberForms = document.forms.length;
for (var index = 0; index < numberForms; index++) {
alert(document.forms[index].name);
}
</script>
</body>
</html>
Save this as
ch11 _ example1.html
. When you load it into your browser, you should see an
alert
box
display the name of the first form. Click the OK button to display the next form's name, and then click
OK a third time to display the third and final form's name.
Within the body of the page you define three forms. You give each form a name and a paragraph of
text.
In the JavaScript code, you loop through the
forms
collection. Just like any other JavaScript array, the
forms
collection has a
length
property, which you can use to determine how many times you need
to loop. Actually, because you know how many forms you have, you can just write the number in.
However, this example uses the
length
property, because that makes it easier to add to the collection
without having to change the code. Generalizing your code like this is a good practice to get into.
The code starts by getting the number of
Form
objects within the
forms
collection and storing that
number in the variable
numberForms
:
var numberForms = document.forms.length;