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[]";
}