Java Reference
In-Depth Information
}
</script>
</head>
<body onload=”window_onload()“>
<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>
</body>
</html>
Save this as ch7_examp1.htm . When you load it into your browser, you should see three alert boxes,
each of which shows the name of a form.
Within the body of the page you defi ne three forms. Each form is given a name and contains a paragraph
of text.
Within the defi nition of the <body/> element, the window_onload() function is connected to the
window object's onload event handler.
<body onload=”window_onload()“>
This means that when the page is loaded, your window_onload() function will be called.
The window_onload() function is defi ned in a script block in the head of the page. Within this func-
tion 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 there are, you can just write the number in. However, this example
uses the length property, since that makes it easier to add to the collection without having to change
the function. Generalizing your code like this is a good practice to get into.
The function starts by getting the number of Form objects within the forms array and storing that
number in the variable numberForms.
function window_onload()
{
var numberForms = document.forms.length;
Next you defi ne a variable, formIndex , to be used in the for loop.
var formIndex;
for (formIndex = 0; formIndex < numberForms; formIndex++)
{
alert(document.forms[formIndex].name);
}
}
Search WWH ::




Custom Search