Reputation: 125
Trying to get a little help with this js code, it is supposed to check and un-check all boxes by ticking the top checkbox. It is old code which I am trying to revive and I am a complete novice to js but willing to learn. I tried several online code checkers but they didnt make any sense to me.
function toggleChecks(field){
if(document.myform.toggleAll.checked == true){
for(i=0; i < field.length; i++){
field[i].checked = true;
}
} else {
for(i=0; i < field.length; i++){
field[i].checked = false;
}
}
}
<div class="s-12 l-five">
<div class="box chkBox" style="background-color: #CCC;"><input name ="toggleAll" id ="toggleAll" type ="checkbox" onclick ="toggleChecks(document.myform.cb)"/></div>
</div>
<div class="s-12 l-five">
<div class="box chkBox"><input name ="toggleAll" id ="toggleAll" type ="checkbox" onclick ="toggleChecks(document.myform.cb)"/></div>
</div>
<div class="s-12 l-five">
<div class="box chkBox"><input name ="toggleAll" id ="toggleAll" type ="checkbox" onclick ="toggleChecks(document.myform.cb)"/></div>
</div>
Upvotes: 0
Views: 39
Reputation: 2530
Select all the check boxes and listen for a click on the first checkbox, check/uncheck all the check boxes according to the status of the first check box
const field = document.querySelectorAll('input[type ="checkbox"]');
function toggleChecks(){
if(event.target.checked){
for(i=0; i < field.length; i++){
field[i].checked = true;
}
} else {
for(i=0; i < field.length; i++){
field[i].checked = false;
}
}
}
<div class="s-12 l-five">
<div class="box chkBox" style="background-color: #CCC;"><input name ="toggleAll" id ="toggleAll" type ="checkbox" onclick ="toggleChecks()"/></div>
</div>
<div class="s-12 l-five">
<div class="box chkBox"><input name ="toggle" id ="toggle1" type ="checkbox"></div>
</div>
<div class="s-12 l-five">
<div class="box chkBox"><input name ="toggle" id ="toggle2" type ="checkbox"></div>
</div>
Upvotes: 1