EN
JavaScript - onchange event for input checkbox element example
4
points
In this article, we want to show different ways to handle change event for input checkbox element using JavaScript.
1. onchange
attribute example
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<body>
<label>
<input type="checkbox" onchange="onChange(this)" /> Agreement
</label>
<script>
function onChange(element) {
console.log('Agreement changed to ' + element.checked);
}
</script>
</body>
</html>
2. onchange
property example
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<body>
<label>
<input id="agreement" type="checkbox" /> Agreement
</label>
<script>
var agreement = document.querySelector('#agreement');
agreement.onchange = function(element) {
console.log('Agreement changed to ' + agreement.checked);
};
</script>
</body>
</html>
3. addEventListener
method example
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<body>
<label>
<input id="agreement" type="checkbox" /> Agreement
</label>
<script>
var agreement = document.querySelector('#agreement');
agreement.addEventListener('change', function(element) {
console.log('Agreement changed to ' + agreement.checked);
});
</script>
</body>
</html>