skip to Main Content

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


  1. 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:

    const cbs=document.querySelectorAll(".checkboxes");
    cbs.forEach(cb=>cb.onclick=ev=>cbs.forEach(c=>c.checked=(c==ev.target&&ev.target.checked || false)));
    <input type="checkbox" class="checkboxes" value="1"> 1<br>
    <input type="checkbox" class="checkboxes" value="2"> 2<br>
    <input type="checkbox" class="checkboxes" value="3"> 3<br>
    <input type="checkbox" class="checkboxes" value="4"> 4<br>
    <input type="checkbox" class="checkboxes" value="5"> 5<br>
    <input type="checkbox" class="checkboxes" value="6"> 6<br>

    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 the cbs collection’s elements c is set to either false, if the current checkbox c in that loop is not identical to the clicked one (cb) or to the clicked value if they are identical.

    Login or Signup to reply.
  2. assigning a single event listener to a parent element and using event bubbling to handle events for multiple child elements.

    let checkboxes = document.querySelectorAll(".checkboxes");
    
    checkboxes.forEach(checkbox => {
      checkbox.addEventListener("change", function() {
        checkboxes.forEach(checkbox => {
          if (checkbox != this) {
            checkbox.checked = false;
          }
        });
      });
    });
    .checkboxes {
      margin: 10px;
    }
    <input type="checkbox" class="checkboxes">
    <input type="checkbox" class="checkboxes">
    <input type="checkbox" class="checkboxes">
    <input type="checkbox" class="checkboxes">
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search