简体   繁体   中英

Check/Uncheck all checkboxes in a grid view

I am trying to implement the feature of checking and unchecking all checkboxes in a grid view at once. I created a main checkbox that will be used to check all the checkboxes at once

<input id="main-checkbox" type="checkbox" name="messages-checkall" value="all" checked="checked" onclick='checkedAll();'>

The checkedAll() function is implemeted as follows

<script type='text/javaScript'>
    function checkedAll () {
        var inputs = document.getElementsByTagName('input');
        var checkboxes = [];
        if (document.getElementById('main-checkbox').checked === "checked") {check = false} else {check = true};
        for (var i = 0; i < inputs.length; i++) {
            if (inputs[i].type == 'checkbox') {
                inputs[i].checked = check;
            }
        }
    }
</script>

but this is not working.

Note - I cannot create a form with all the checkboxes and then handle all the checkboxes in the form.

Please tell if you want other detail.

Change

if (document.getElementById('main-checkbox').checked === "checked") {check = false} else {check = true};

To

var check = document.getElementById('main-checkbox').checked
var objCheckBoxes = document.getElementById('containerId').getElementsByTagName('input');

var countCheckBoxes = objCheckBoxes.length;
if(!countCheckBoxes)
{
    objCheckBoxes.checked = true/false;
}
else
{
    for(var i = 0; i < countCheckBoxes; i++)
    {
        objCheckBoxes[i].checked = true/false;
    }
}

In html

<ul id="containerId">
 <li><input type="checkbox" name="selected" value="Some text description 1"></li>
 <li><input type="checkbox" name="selected" value="Some text description 2"></li>
</ul>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM