Episode 15 of 18
Checkboxes & Change Events
Handle checkbox inputs — listen for change events, check the checked state, and update the DOM based on checkbox selections.
Checkboxes & Change Events
Checkboxes are unique form elements — they do not have a text value like inputs. Instead, they have a checked property (boolean). Combined with the change event, you can build interactive filter and toggle UIs.
The checked Property
<label>
<input type="checkbox" id="agree"> I agree to the terms
</label>
var checkbox = document.querySelector('#agree');
console.log(checkbox.checked); // false (unchecked)
checkbox.addEventListener('change', function() {
console.log('Checked:', this.checked); // true or false
});
Toggling Content
<label><input type="checkbox" class="filter" value="CSS"> CSS</label>
<label><input type="checkbox" class="filter" value="JS"> JavaScript</label>
<div class="output"></div>
var filters = document.querySelectorAll('.filter');
var output = document.querySelector('.output');
filters.forEach(function(filter) {
filter.addEventListener('change', function() {
var selected = [];
filters.forEach(function(f) {
if (f.checked) selected.push(f.value);
});
output.textContent = 'Selected: ' + selected.join(', ');
});
});
Select All / Deselect All
var selectAll = document.querySelector('#select-all');
var items = document.querySelectorAll('.item-checkbox');
selectAll.addEventListener('change', function() {
var isChecked = this.checked;
items.forEach(function(item) {
item.checked = isChecked;
});
});
Key Takeaways
- Use the
checkedproperty (boolean) instead ofvaluefor checkboxes - The
changeevent fires when a checkbox is toggled - Loop through checkboxes and check
.checkedto find selected items - Set
.checked = true/falseprogrammatically to control checkboxes