Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autocheck checkboxes in javascript

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>
But it don't work.What is the problem?
like image 546
sergiu reznicencu Avatar asked Aug 17 '26 11:08

sergiu reznicencu


1 Answers

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;
}
like image 96
undefined Avatar answered Aug 19 '26 03:08

undefined



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!