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!
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.
prop() You can use the prop() method to check or uncheck a checkbox, such as on click of a button.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With