javascriptgetelementsbyname

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?


Solution

  • 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>