I'm trying to enable the user to uncheck all checkboxes with the escape key. I found this code snippet that does the job, but by clicking a button.
<form>
<input type="checkbox" name="checkBox" >one<br>
<input type="checkbox" name="checkBox" >two<br>
<input type="checkbox" name="checkBox" >three<br>
<input type="checkbox" name="checkBox" >four<br>
<input type=button name="CheckAll" value="Select_All" onClick="check(true,10)">
<input type=button name="UnCheckAll" value="UnCheck All Boxes" onClick="check(false,10)">
</form>
function check(checked,total_boxes){
for ( i=0 ; i < total_boxes ; i++ ){
if (checked){
document.forms[0].checkBox[i].checked=true;
}else{
document.forms[0].checkBox[i].checked=false;
}
}
}
document.addEventListener('keydown', (event) => {
if (event.key === 'Escape') {
// uncheck all checkboxes
}
});
The code doesn't work on checkboxes that are not in a tag. Sometimes I use checkboxes for CSS only on-click events, which are not inside of a form. The use case here is for CSS only menu pop-ups and drop-downs. I'm trying to make them accessible by allowing the user to close with the escape key. Sure, it's not CSS only any more, but I need to improve accessibility.
This should do it:
function allCB(checked){
document.querySelectorAll("input[type=checkbox]").forEach(cb=>cb.checked=checked)
}
document.addEventListener('keydown',_=>event.key === 'Escape' && allCB(false));
document.querySelector("form").addEventListener('click',ev=>ev.target.type=="button" && allCB(ev.target.name=="CheckAll"));
<form>
<label><input type="checkbox" name="checkBox">one</label><br>
<label><input type="checkbox" name="checkBox">two</label><br>
<label><input type="checkbox" name="checkBox">three</label><br>
<label><input type="checkbox" name="checkBox">four</label><br>
<input type=button name="CheckAll" value="Select_All">
<input type=button name="UnCheckAll" value="UnCheck All Boxes">
</form>