I want to uncheck all other checkboxes aside from the checked one.
I tried this function but it doesn’t work properly.
let wordch = document.getElementsByClassName('checkboxes');
function uncheck(){
for(let i = 0; i < numbers.length; i++){
if(wordch[i].checked != false){
if (i - 1 > 0 && i + 1 < wordch.length) {
wordch[i - 1].checked = false;
wordch[i + 1].checked = false;
}
}
}
}
2
Answers
As I mentioned in my comment, the best solution would involve radio buttons instead of checkboxes. But if you insist on using checkboxes, then the following could be one way to go:
The collection
cbs
contains all checkboxes of the given class.checkboxes
. A.forEach()
loop over this collection assigns the.onclick
event handler to each individual checkbox. Within the event handler the.checked
state of each of thecbs
collection’s elementsc
is set to eitherfalse
, if the current checkboxc
in that loop is not identical to the clicked one (cb
) or to the clicked value if they are identical.assigning a single event listener to a parent element and using event bubbling to handle events for multiple child elements.