Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't selecting a checkbox using document.querySelectorAll() working?

I have the following code, mostly from How can I select all checkboxes from a form using pure JavaScript and it's just not working.

Test.html

<html>
    <head>
    <script>
    function select(){
        var inputs = document.querySelectorAll("input[type='checkbox']");
        for(var i = 0; i < inputs.length; i++) {
            inputs[i].checked = true;   
        }
    }
    </script>
    </head>
    <body>
        <form id="myId" name="myForm">
        <input type="checkbox" value="1"/> 1
        <input type="checkbox" value="2"/> 2
        <input type="checkbox" value="3"/> 3
        <input type="button" onclick="select()"  value="Select all"/>
        </form>
    </body>
</html>

Clicking the button does nothing. I must be doing something really wrong here but I just can't pick it out.

like image 229
Joseph Avatar asked Feb 23 '26 23:02

Joseph


1 Answers

Try this...

<html>
    <head>
    <script>
    function test(){
        var inputs = document.querySelectorAll("input[type='checkbox']");
        for(var i = 0; i < inputs.length; i++) {
            inputs[i].checked = true;   
        }
    }
    </script>
    </head>
    <body>
        <form id="myId" name="myForm">
        <input type="checkbox" value="1"/> 1
        <input type="checkbox" value="2"/> 2
        <input type="checkbox" value="3"/> 3
        <input type="button" onclick="test()"  value="Select all"/>
        </form>
    </body>
</html>
like image 145
Deenadhayalan Manoharan Avatar answered Feb 26 '26 12:02

Deenadhayalan Manoharan



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!