2

I want to create a loop over element in javascript , my html is:

<input type="checkbox" name="menu[]" value="0">
<input type="checkbox" name="menu[]" value="1">
<input type="checkbox" name="menu[]" value="2">

and javascript is

window.onload = function() {
    var x = document.getElementsByName("menu");
    for (i = 0; i < x.length; i++) {
        if (x[i].type == "checkbox") {
            x[i].checked = true;
        }
    }

}

but no element was detected!!!! try alert(x.length) and you seen 0!!

2
  • 1
    Why would it be detected??? menu isn't the name!!!! Commented Feb 4, 2015 at 18:23
  • @BhojendraNepal - What if the OP needs to collect the checkbox values in a language like PHP? Commented Feb 4, 2015 at 18:24

1 Answer 1

3

The element name is menu[], just like it says in the HTML source.

window.onload = function() {
    var x = document.getElementsByName("menu[]"), i;
    for (i = 0; i < x.length; i++) {
        if (x[i].type == "checkbox") {
            x[i].checked = true;
        }
    }
}
<input type="checkbox" name="menu[]" value="0">
<input type="checkbox" name="menu[]" value="1">
<input type="checkbox" name="menu[]" value="2">
<p>All checkboxes named <b>menu[]</b> have been checked.</p>

HTML does not care about the square brackets. They have no meaning, they are just like letters.

The fact that, for example, PHP treats them specially is nothing that HTML is concerned with.

P.S. Don't forget to declare your loop counter i, otherwise it will be global, and you don't want a global loop counter.

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

1 Comment

Of course it works. Run the code snippet in my answer if you don't believe it.

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.