Reputation:
why we use 0 in document.form[0].if i use 1 insteadof 0 it will not work anybody please explain that. my code is:
<!DOCTYPE html>
<html>
<head>
<script>
function preferedBrowser() {
//here if i use document.forms[1] it will not work
prefer = document.forms[0].browsers.value;
alert("You prefer browsing internet with " + prefer);
}
</script>
</head>
<body>
<form>
Choose which browser you prefer:
<select id="browsers" onchange="preferedBrowser()">
<option>Chrome</option>
<option >Internet Explorer</option>
<option>Firefox</option>
</select>
</form>
</body>
</html>
Upvotes: 0
Views: 3233
Reputation: 4038
document.forms returns the collection of all the forms of a document. So as its returning a collection you need to address specific form using it's index. There are other ways also to get specific form i.e. using id attribute
<form id="myForm"></form>
var aForm = document.getElementById("myForm");
In your case it's a single form so you have to address that using 0 index. But in many web pages developers need multiple forms. So there you might need to use the correct index.
Still its preferable to call a specific form with it's id attribute. Who wants to call something with a number rather a name. As id is to be unique for each element so you will get lots of benefit out of it.
Upvotes: 1
Reputation: 13848
document.forms
, plural form. It's an array-like data structure (HTMLCollection actually), and is zero-based.
Upvotes: 0
Reputation: 568
Array's in Javascript start from index "0" not from "1". So, if you have only one form you can access it from "0th" index. if you have two forms you can access the second form using document.form[1] ....and so on...
Upvotes: 0
Reputation: 201
In a HTML page with multiple form
You access the first form by index 0 i,e document.forms[0];
and the second one by index 1 and so on.
Upvotes: 1
Reputation: 5381
document.form
is an array of the form elements in the document's body, and array start with index of 0, and since you only have 1 form the document.form
array has only 1 element in it witch it's index is 0
Upvotes: 1
Reputation: 3844
It is because you have only 1 <form>
object in your html page.
The array is zero based.
Upvotes: 1