1

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.

2
  • Please note that IDs should be unique! If you want an array, do it with same names rather than IDs. Also not that the pseudo label javascript: is unnecessary anywhere except IE browsers which have a VBScript as the first script on the page Commented Nov 2, 2012 at 10:48
  • Also note that since you are using document.forms access, I would expect form.url1 to be equivalent to form.elements["url1"] and hence use the name of the element. In your case you seem to manage to confuse the issue by having same IDs which is illegal Commented Nov 2, 2012 at 10:58

1 Answer 1

2

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 url1

So form.url1 becomes a NodeList consisting of those two elements.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.