Search code examples
javascriptcheckboxonchange

Checking if checkboxes are checked ornot, returns addEventListener is not a function


Hi I got the following code snippet where im trying to print a console.log dependent on if a checkbox has been checked or not.

var checkbox = document.querySelectorAll('.customer-club-widget__gender__categories .form__input-checkbox');

checkbox.addEventListener("change", function() {

    var isChecked = checkbox.checked;
    if(isChecked){ //checked
        console.log('checked');
    }else{ //unchecked
        console.log('unchecked');
    }
});

I keep getting the following error:

Uncaught TypeError: checkbox.addEventListener is not a function and a cant figure out why this is happening.


Solution

  • You're getting the error since querySelectorAll() return a array of elements and you're trying to attach the event to this array, else you should loop through it to attach the change event to every element inside, like :

    //Loop through the array elements and attach the event
    for (var i = 0; i < checkbox.length; i++) {
      checkbox[i].addEventListener("change", checkedOrNot);
    }
    
    //Define separate function
    function checkedOrNot() {
      var isChecked = this.checked;
    
      if (isChecked) { //checked
        console.log('checked');
      } else { //unchecked
        console.log('unchecked');
      }
    }
    

    Hoep this helps.

    var checkbox = document.querySelectorAll('.customer-club-widget__gender__categories .form__input-checkbox');
    
    for (var i = 0; i < checkbox.length; i++) {
      checkbox[i].addEventListener("change", checkedOrNot);
    }
    
    function checkedOrNot() {
      var isChecked = this.checked;
    
      if (isChecked) { //checked
        console.log('checked');
      } else { //unchecked
        console.log('unchecked');
      }
    }
    <div class="customer-club-widget__gender__categories">
      <input type="checkbox" class="form__input-checkbox" /> A
      <br>
      <input type="checkbox" class="form__input-checkbox" /> B
      <br>
      <input type="checkbox" class="form__input-checkbox" /> C 
      <br>
      <input type="checkbox" class="form__input-checkbox" /> D
    </div>