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 can 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 select the checkbox with querySelector
.
Then we call checkbox.addEventListener
to add an event listener for the change event.
We get the checked value of the checkbox with e.target.checked
.
If it’s true
, it’s checked.
Otherwise, it’s not.
Conclusion
To add a checkbox check event listener with JavaScript, we can listen for the change event.