Reputation: 971
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!!
Upvotes: 2
Views: 1479
Reputation: 338326
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.
Upvotes: 3