Sometimes, we want to watch for checkbox change with JavaScript.
In this article, we’ll look at how to watch for checkbox change with JavaScript.
How to watch for checkbox change with JavaScript?
To watch for checkbox change with JavaScript, we call addEventListener
with 'change'
on the checkbox input element.
For instance, we write
<input type="checkbox" />
to add a checkbox input.
Then we write
const checkbox = document.getElementById("myCheckbox");
checkbox.addEventListener("change", (event) => {
if (event.currentTarget.checked) {
alert("checked");
} else {
alert("not checked");
}
});
to call addEventListener
with 'change'
and the change event handler callback to run the callback when we change the value of the checkbox.
In the callback, we use checked
property to get the checked value of the checkbox.
Conclusion
To watch for checkbox change with JavaScript, we call addEventListener
with 'change'
on the checkbox input element.