mOrloff
mOrloff

Reputation: 2617

Javascript: Why is FOR loop skipping every other match?

I'm currently getting 5 results from my .getElementsByName() query, and looping though them proceeds as expected when throwing a simple alert(), but as soon as I try to set new names for those results, it's skipping my second and fourth matches.

SOURCE:

<form>
    <input type="text" />
    <input type="checkbox" name="target" value=1 />
    <input type="checkbox" name="target" value=2 />
    <input type="checkbox" name="target" value=3 />
    <input type="checkbox" name="target" value=4 />
    <input type="checkbox" name="target" value=5 />
    <input type="text" />
    <input type="checkbox" name="test" />
    <input type="checkbox" name="test" />
    <input type="checkbox" name="test" />
</form>


When I try:

window.onload = function() {
    var fields = document.getElementsByName("target");

    for (var i = 0; i < fields.length; i++) {
        alert( fields[i].value );
    }
}

It throws an alert for all five values.


HOWEVER, when I try this instead:

for (var i = 0; i < fields.length; i++) {
    fields[i].name = 'target[]';
}

it only renames every other one (0,2,4).

What am I missing?

Upvotes: 1

Views: 62

Answers (2)

gavgrif
gavgrif

Reputation: 15509

I agree with @Isaac regarding the cause - but I have an alternate solution if you change to a querySelectorAll as below - it will work for all checkboxes and apply the altered name[].

window.onload = function() {
    var fields = document.querySelectorAll("[name='target']");
    for (var i = 0; i < fields.length; i++) {
         fields[i].name = 'target[]';
    }
}
<form>
    <input type="text" />
    <input type="checkbox" name="target" value=1 />
    <input type="checkbox" name="target" value=2 />
    <input type="checkbox" name="target" value=3 />
    <input type="checkbox" name="target" value=4 />
    <input type="checkbox" name="target" value=5 />
    <input type="text" />
    <input type="checkbox" name="test" />
    <input type="checkbox" name="test" />
    <input type="checkbox" name="test" />
</form>

Upvotes: 1

Isaac
Isaac

Reputation: 11805

Try

for (var i = fields.length - 1; i >= 0; i--) {
    fields[i].name = 'target[]';
}

I think this is because when you change the fields name, and document::getElementsByName is a "magical" list (see this question), it is removed from the list you're iterating through if you change its name.

Upvotes: 1

Related Questions