Lesson 20: Checkboxes
Learn how to work with checkboxes in JavaScript to create multi-selection interfaces and forms.
20.1 Understanding Checkboxes
Checkboxes are form controls that allow users to select multiple options from a group of choices. They are essential for forms where multiple selections are allowed.
20.1.1 Basic Checkbox Selection
Example 20.1: Single Checkbox
This example shows how to check the status of a single checkbox.
// HTML
<div class="checkbox-group">
<div class="checkbox-option">
<input type="checkbox" id="terms" name="terms">
<label for="terms">I agree to the terms and conditions</label>
</div>
<button type="button" onclick="checkTerms()">
Verify Agreement
</button>
</div>
// JavaScript
function checkTerms() {
const termsCheckbox = document.getElementById('terms');
if (termsCheckbox.checked) {
alert("Thank you for agreeing to the terms!");
} else {
alert("Please agree to the terms to continue.");
}
}
20.1.2 Handling Multiple Checkboxes
Example 20.2: Multiple Checkbox Selection
This example demonstrates how to get values from multiple selected checkboxes.
// HTML
<div class="checkbox-group">
<div class="checkbox-option">
<input type="checkbox" id="apple" name="fruits" value="Apple">
<label for="apple">Apple</label>
</div>
<!-- More options -->
<button type="button" onclick="getSelectedFruits()">
Show Selected
</button>
</div>
// JavaScript
function getSelectedFruits() {
const checkboxes = document.querySelectorAll('input[name="fruits"]:checked');
const selectedValues = Array.from(checkboxes).map(cb => cb.value);
if (selectedValues.length > 0) {
alert("Selected fruits: " + selectedValues.join(", "));
} else {
alert("Please select at least one fruit.");
}
}
20.2 Advanced Checkbox Techniques
Explore more sophisticated techniques for working with checkboxes in real-world applications.
20.2.1 Toggle All Checkboxes
Example 20.3: Master Checkbox
This example shows how to use a master checkbox to select/deselect all options.
// HTML
<div class="checkbox-group">
<div class="checkbox-option">
<input type="checkbox" id="selectAll">
<label for="selectAll">Select All</label>
</div>
<div class="checkbox-option">
<input type="checkbox" class="item" name="items" value="Item1">
<label>Item 1</label>
</div>
<!-- More options -->
</div>
// JavaScript
document.getElementById('selectAll').addEventListener('change', function() {
const items = document.querySelectorAll('.item');
items.forEach(item => {
item.checked = this.checked;
updateCheckboxUI(item);
});
});
// Update UI when individual checkboxes change
document.querySelectorAll('.item').forEach(item => {
item.addEventListener('change', function() {
updateCheckboxUI(this);
updateSelectAllCheckbox();
});
});
function updateCheckboxUI(checkbox) {
const container = checkbox.closest('.checkbox-option');
if (checkbox.checked) {
container.classList.add('selected');
} else {
container.classList.remove('selected');
}
}
function updateSelectAllCheckbox() {
const items = document.querySelectorAll('.item');
const allChecked = items.length > 0 &&
Array.from(items).every(item => item.checked);
document.getElementById('selectAll').checked = allChecked;
}
20.2.2 Checkbox Validation in Forms
Example 20.4: Subscription Form
This example demonstrates form validation with checkboxes using the onsubmit event.
// HTML
<form id="subscriptionForm" onsubmit="return validateForm()">
<div class="form-group">
<label>Select your interests:</label>
<div class="checkbox-group">
<div class="checkbox-option">
<input type="checkbox" id="tech" name="interests" value="Technology">
<label for="tech">Technology</label>
</div>
<!-- More options -->
</div>
</div>
<button type="submit" class="submit-btn">Subscribe</button>
<div class="validation-summary" id="formValidation">
<h4>Please fix the following errors:</h4>
<ul id="formErrors"></ul>
</div>
</form>
// JavaScript
function validateForm() {
const interests = document.querySelectorAll('input[name="interests"]:checked');
const errors = [];
if (interests.length === 0) {
errors.push("Please select at least one interest");
}
if (errors.length > 0) {
const errorList = document.getElementById('formErrors');
errorList.innerHTML = errors.map(e => `<li>${e}</li>`).join('');
document.getElementById('formValidation').style.display = 'block';
return false;
}
// Form is valid
alert("Subscription successful!");
return true;
}
20.3 Real-World Applications
These checkbox techniques are essential in many web applications. Here are practical examples:
20.3.1 Shopping Cart
Example 20.5: Shopping Cart with Checkboxes
This example demonstrates a shopping cart where users can select items using checkboxes and calculate the total.
// HTML
<div class="cart-container">
<div class="cart-item">
<div>
<div class="checkbox-option">
<input type="checkbox" id="item1" class="cart-item" data-price="25">
<label for="item1">JavaScript Book - $25.00</label>
</div>
</div>
</div>
<!-- More items -->
<div class="cart-total" id="cartTotal">Total: $0.00</div>
<button type="button" onclick="calculateTotal()">
Calculate Total
</button>
</div>
// JavaScript
function calculateTotal() {
const items = document.querySelectorAll('.cart-item:checked');
let total = 0;
items.forEach(item => {
const price = parseFloat(item.getAttribute('data-price'));
total += price;
});
document.getElementById('cartTotal').textContent =
`Total: $${total.toFixed(2)}`;
}
// Update UI when items are selected
document.querySelectorAll('.cart-item').forEach(item => {
item.addEventListener('change', function() {
updateCheckboxUI(this);
});
});