Home

Javascript Check All Checkboxes

Blog Date 23 April 2021

TLDR

    <input type="checkbox" onclick="DoCheck(this)" />(All)

    <script>

        function DoCheck(x) {
            var ctrls = document.getElementsByTagName('input');
            for (var i = 0; i < ctrls.length; i++) {
                var mybox = ctrls[i];
                if (mybox.type == "checkbox") {
                    mybox.checked = x.checked
                }
            }
        }

    </script>

Imagine if you will you have a table or repeater or datagrid or whatnot. In HTML they'll all end up as a table anyhow. In said table you have a column with checkboxes. You wish to be able to check and/or uncheck them all. 

The "primary" checkbox at the top of the above code is the trigger for this. Once clicked the Javascript function is run. It grabs ALL HTML elements that are "input" (ie buttons, textboxes etc) into a var named "ctrls". It loops through these controls to find the ones of type "checkbox". It then matches the found checkbox to the checked or unchecked status of the primary checkbox. 

This works well and is simple BUT it will check/uncheck ALL the checkboxes in a page, not just the ones in the column you're working in. For that you'll need to add a class like you would for CSS then find the class. That's for another day.


Need some code coding? Contact ren@techsolus.co.uk

Reader's Comments

Post Your Comment Posts/Links Rules

Name

Comment

Add a RELEVANT link (not required)

Upload an image (not required)

No uploaded image
Real person number
Please enter the above number below




Home
Admin Ren's Biking Blog