How to add a checkbox check event listener with JavaScript?

Spread the love

Sometimes, we want to add a checkbox check event listener with JavaScript.

In this article, we’ll look at how to add a checkbox check event listener with JavaScript.

How to add a checkbox check event listener with JavaScript?

To add a checkbox check event listener with JavaScript, we listen for the change event.

For instance, we write

<input type="checkbox" name="checkbox" />

to add a checkbox.

Then we write

const checkbox = document.querySelector("input[name=checkbox]");

checkbox.addEventListener("change", (e) => {
  if (e.target.checked) {
    console.log("Checkbox is checked..");
  } else {
    console.log("Checkbox is not checked..");
  }
});

to get the checkbox with querySelector.

And then we add a change listener to it with addEventListener.

In it, we check if the checkbox is checked with the checked property.

If it’s true, then it’s checked.

Conclusion

To add a checkbox check event listener with JavaScript, we listen for the change event.

Leave a Reply

Your email address will not be published. Required fields are marked *