JavaScript - Checkbox change event
A simple code example introducing how to implement a checkbox change event using addEventListener()
in JavaScript.
The HTML has checkboxes with class "checkbox" to detect value changes.
<div class="item-container">
<p id="output">Please check your favorite.</p>
<div class="checkboxs">
<p><input type="checkbox" id="checkbox-a" class="checkbox" name="name" value="A">
<label for="checkbox-a">A</label></p>
<p><input type="checkbox" id="checkbox-b" class="checkbox" name="name" value="B">
<label for="checkbox-b">B</label></p>
<p><input type="checkbox" id="checkbox-c" class="checkbox" name="name" value="C">
<label for="checkbox-c">C</label></p>
</div>
</div>
The target checkboxes are queried with querySelectorAll()
and addEventListener()
is used on each to implement a "change" event to get the changed values.
The code example displays the values and checked status in the output area when checkboxes change.
// Get all target checkboxes
let checkboxs = document.querySelectorAll('.checkbox');
// Add change event to each checkbox
for (let target of checkboxs) {
target.addEventListener(`change`, () => {
console.log(123);
// Display result in output area
document.querySelector(`#output`).innerHTML = `${target.value}:${target.checked}`;
});
}