Question

I have a form with multiple input(text) elements with the same name

<input name="val[]" type="text" />
<input name="val[]" type="text" />
<input name="val[]" type="text" />

Now, say I want to change their names to "val2[]".

This is what I originally wrote:

var vals=document.getElementsByName("val[]");
var valct=vals.length;
    for( var i=0; i<valct; i++ )
        vals[i].name="val2[]";

However this seems to be getting me an error.
From Chrome's developer tool it says "Cannot set property 'name' of undefined"

After thinking for some time, I figured that the element might be deleted after renaming.
Therefore, I changed the last line of the code to:

vals[ 0 ].name="val2[]";

And this works !

But then, I was thinking if I could code it this way:

while( vals=document.getElementsByName("val[]") )
    vals[0].name="val2[]";

This gives me the same error I got above "Cannot set property 'name' of undefined"
I am puzzled. I also tested it with Firefox and the results were the same. (cannot test on IE because I use HTML5 native DnD on the page)

It seems to me that what getElementsByName returns is a queue while changing names acts as removing items from one.
Is this true? or what is the correct explanation for this ?

Was it helpful?

Solution

It happens because you changing attribute, which you are using as selector for document.getElementsByName and it return NodeList object to you, not an Array. NodeList it is a live collection of DOM elements (ref). So after you name attribute modification it will contain less than 3 elements (demostration).

Try to modify you code like an example below, and this will solve you problem, because you will get an static Array instead of NodeList (jsfiddle).

var vals = [].slice.call(document.getElementsByName("val[]"));
var valct = vals.length;
for( var i=0; i<valct; ++i ) {
    vals[i].name="val2[]";
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top