I was trying to group a set of INPUT-elements in a Javascript array and got confused on why I got a multi-dimensional array back (array named ‘urls’ in the code below).
It turned out I had mixed up the fourth element with the same id as the first element.
<html>
<head>
<script language="javascript">
function validate() {
var form = document.forms.conf;
var urls = new Array(form.url1, form.url2, form.url3, form.url4);
alert(urls[0].value); // returns 'undefined'
alert(urls[0][0].value); // works
}
</script>
</head>
<body>
<form name="conf">
<input type="text" name="url1" id="url1">
<input type="text" name="url2" id="url2">
<input type="text" name="url3" id="url3">
<input type="text" name="url4" id="url1"><br />
<button type="button" onclick="javascript:validate();">Push me</button>
</form>
</body>
</html
My question is, why does this happen? What relationship does the HTML attribute ‘id’ have to ‘document.forms.form_name.element’? And why does it cause it to put it in a multi-dimensional array?
The behavior seems to be the same cross-browser too, so it have to be some definition I’m not aware of.
A form will have a property for each form control that has a name or id. The name of that property will be the same as the name or id. If multiple elements share a name (or, illegally, an id) then the property will contain an NodeList instead of a single HTMLElementNode.
The first input has the name (and id)
url1.The last input has the id
url1So
form.url1becomes a NodeList consisting of those two elements.