Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript: Unchecking all checkboxes

Tags:

javascript

I have problem dealing with unchecking all checkboxes. When I click on a toggle all checkbox, it could check all checkboxes. But if I uncheck the toggle all checkbox, nothing happens. All checkboxes are not unchecked. Below is my coding in javascript:

<script>
var isAllCheck = false;
function togglecheckboxes(cn){

    var cbarray = document.getElementsByName(cn);
    for(var i = 0; i < cbarray.length; i++){

        if( isAllCheck == false ){
            cbarray[i].checked = "true";
            //alert( "it is false" );
        }else{ 
            cbarray[i].removeAttribute("checked");
            //alert( "it is true" );
        }
}   
isAllCheck = !isAllCheck;   
}
</script>

I had even tried this coding, but still failed:

<script>
var isAllCheck = false;
function togglecheckboxes(cn){

    var cbarray = document.getElementsByName(cn);
    for(var i = 0; i < cbarray.length; i++){

        if( isAllCheck == false ){
            cbarray[i].checked = "true";
            //alert( "it is false" );
        }else{ 
            cbarray[i].checked = "false";
            //alert( "it is true" );
        }
}   
isAllCheck = !isAllCheck;   
}
</script>

Below is my PHP coding for your reference:

echo "\t<div class='item'>
<span class='CDTitle'>{$cd['CDTitle']}</span>
<span class='CDYear'>{$cd['CDYear']}</span>
<span class='catDesc'>{$cd['catDesc']}</span>
<span class='CDPrice'>{$cd['CDPrice']}</span>
<span class='chosen'><input type='checkbox' name='cd[]' value='{$cd['CDID']}' title='{$cd['CDPrice']}' /></span>
</div>\n";

Any tips on resolving this problem. Thanks in advance!

like image 343
Boon Avatar asked Mar 26 '13 14:03

Boon


People also ask

How do you select or deselect all checkboxes using Javascript?

For the input types as button, we have created one button for selecting the checkboxes where onClick (), the selects () function will be invoked and the other one for deselecting the checkboxes (if selected any/all) where onClick () the deselect () function will be invoked.

How do I uncheck a checkbox in Javascript?

prop() You can use the prop() method to check or uncheck a checkbox, such as on click of a button.


1 Answers

Update

As per comments, Array.from is not necessary anymore on modern browsers, so you could do

document.querySelectorAll('input[type=checkbox]').forEach(el => el.checked = isAllCheck);

Original answer

After validating that isAllCheck is correct with your UI logic, you may do both with a simple vanilla-js one-liner

Array.from(document.querySelectorAll('input[type=checkbox]')).forEach(el => el.checked = isAllCheck);
like image 150
Ulisses Caon Avatar answered Oct 06 '22 01:10

Ulisses Caon