1

https://www.w3schools.com/code/tryit.asp?filename=GKTIU8SG2RMP

document.addEventListener('DOMContentLoaded', function () {
  var checkbox = document.querySelector('input[type="checkbox"]');

  checkbox.addEventListener('change', function () {
    if (checkbox.checked) {
      // do this
      console.log('Checked');
    } else {
      // do that
      console.log('Not checked');
    }
  });
});

Above the link, when the first button is clicked, I got its status perfectly (either checked or not checked). However, for the second button, it does not show the status (either checked or not checked). How do I solve this problem? Thank you very much for your attention. NOTE: I am using for loop for the button so there will be many buttons and it is inefficient if the solution were to declare the buttons one by one.

Biruk
  • 23
  • 1
  • 5
Testing Su
  • 43
  • 4

2 Answers2

4

querySelector finds the first element that matches the selector. If you want to find more than one, use querySelectorAll which returns a NodeList (similar to an array). For instance:

function checkboxChangeHandler() {
    if (this.checked) { // <== Note use of `this`
        // do this
        console.log('Checked');
    } else {
        // do that
        console.log('Not checked');
    }
}
document.addEventListener('DOMContentLoaded', function () {
    var checkboxes = document.querySelectorAll('input[type="checkbox"]');
    checkboxes.forEach(function(checkbox) {
        checkbox.addEventListener('change', checkboxChangeHandler);
    });
});

Note: That code is written in ES5 since your original code was, but normally I'd use ES2015+ features like const and iterability.

Note 2: That code relies on the forEach method of NodeList, which was added around 2017 or so. But it's easily polyfilled for obsolete environments, I describe how in this other SO answer.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
2

document.querySelector returns a single (first) result from the DOM, instead of all nodes. If you need a list of all elements matching the specified selectors, you should use document.querySelectorAll instead. So in your case:

const checkboxes = document.querySelectorAll('input[type="checkbox"]');

checkboxes.forEach(function (checkbox) {
  checkbox.addEventListener('change', function () {
    if (checkbox.checked) {
      // do this
      console.log('Checked');
    } else {
      // do that
      console.log('Not checked');
    }
  });
});