Example of Selecting, Deselecting, and Inverting All Checkboxes in JavaScript
Showcase
The checkboxes above can be toggled individually, but four special buttons provide the following functions. This kind of implementation is especially useful when dealing with a large number of checkboxes.
- Æ: Select only the A, B, C, D, E checkboxes
- ∅: Deselect all checkboxes
- ∀: Select all checkboxes
- ¬: Invert all checkboxes
Code
HTML
<div align="center" style="user-select: none;">
<input type="checkbox" id="FN_AE" hidden>
<label for="FN_AE">Æ</label>
<input type="checkbox" id="FN_NO" hidden>
<label for="FN_NO">∅</label>
<input type="checkbox" id="FN_AL" hidden>
<label for="FN_AL">∀</label>
<input type="checkbox" id="FN_CP" hidden>
<label for="FN_CP">¬</label>
<input type="checkbox" id="A"><label for="A">A</label>
<input type="checkbox" id="B"><label for="B">B</label>
<input type="checkbox" id="C"><label for="C">C</label>
<input type="checkbox" id="D"><label for="D">D</label>
<input type="checkbox" id="E"><label for="E">E</label>
<input type="checkbox" id="F"><label for="F">F</label>
<input type="checkbox" id="G"><label for="G">G</label>
<input type="checkbox" id="H"><label for="H">H</label>
<input type="checkbox" id="I"><label for="I">I</label>
<input type="checkbox" id="J"><label for="J">J</label>
</div>
<div align="center" style="user-select: none;">
: Prevents the checkboxes from being dragged.id="FN\_*
: Specifies the IDs of the buttons to which JavaScript will assign functionality.
javascript
<script>
function setCheckboxState(condition) {
document.querySelectorAll("input[type='checkbox']").forEach((checkbox) => {
const id = checkbox.id;
if (condition === "AE") {
checkbox.checked = ["A", "B", "C", "D", "E"].includes(id);
} else if (condition === "ALL") {
checkbox.checked = true;
} else if (condition === "EMPTY") {
checkbox.checked = false;
} else if (condition === "CP") {
checkbox.checked = !checkbox.checked;
}
});
}
document.getElementById("FN_AE").addEventListener("click", () => setCheckboxState("AE"));
document.getElementById("FN_NO").addEventListener("click", () => setCheckboxState("EMPTY"));
document.getElementById("FN_AL").addEventListener("click", () => setCheckboxState("ALL"));
document.getElementById("FN_CP").addEventListener("click", () => setCheckboxState("CP"));
</script>
querySelectorAll("input[type='checkbox']")
: Identifies all checkboxes on the page and assigns actions depending on which button is clicked.addEventListener("click", () => ...
: Actually sets the state of the checkboxes when each button is clicked.