A single control can toggle an entire checkbox group. The control can be a button whose label changes, or a master checkbox whose checked state is copied to the group.
Open single-control democonst boxes = [...document.querySelectorAll('input[name="check_list"]')];
const toggle = document.getElementById("toggleAll");
toggle.addEventListener("click", () => {
const check = !boxes.every((box) => box.checked);
boxes.forEach((box) => { box.checked = check; });
toggle.textContent = check ? "Uncheck All" : "Check All";
});
The original tutorial checks the button’s displayed value to decide what happens next. Deriving the action from the checkbox group avoids tying program state to button text.
const master = document.getElementById("master");
const boxes = document.querySelectorAll('input[name="check_list"]');
master.addEventListener("change", () => {
boxes.forEach((box) => {
box.checked = master.checked;
});
});
const count = boxes.filter((box) => box.checked).length;
master.checked = count === boxes.length;
master.indeterminate = count > 0 && count < boxes.length;
indeterminate is a visual state set by JavaScript. It is useful when only some child boxes are checked.
See the two-button and master-checkbox tutorial.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.