I have multiple checkboxes on my page and a "Select all" button.I want ,that when i press the select button, all elements on the page to be checked.This is the javascript code that i have tried:
<script>
function selectall() {
for (var i = 0; i < document.getElementsByName("ch").length; i++) {
document.getElementsByName(ch[i]).checked = true;
}
}
</script>
And here' is the html:
<form action="analize.php" method="POST" enctype="multipart/form-data">
<input type="button" onclick="selectall()" value="SELECT ALL" />
<input type="checkbox" name="ch[]" value="a" align="MIDLE" />
<input type="checkbox" name="ch[]" value="b" align="MIDLE" />
<input type="checkbox" name="ch[]" value="c" align="MIDLE" />
</form>
The name attribute of the target elements is ch[] not ch. Also .getElementsByName(ch[i])
should be .getElementsByName('ch[]')[i].
for (var i = 0; i < document.getElementsByName("ch[]").length; i++) {
document.getElementsByName('ch[]')[i].checked = true;
}
You could also cache the NodeList which is more efficient than querying the DOM in each iteration:
var nodeList = document.getElementsByName("ch[]");
for (var i = 0; i < nodeList.length; i++) {
nodeList[i].checked = true;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With