JavaScript Example for Selecting, Deselecting, and Toggling a Series of Checkboxes with Shift Click
Showcase
When you select one of the checkboxes above, hold Shift and click another checkbox; all checkboxes between the two will be toggled (checked ↔ unchecked). This feature is useful when dealing with a large number of checkboxes, and is particularly handy in contexts such as lists of posts or file listings where items do not immediately appear as checkboxes.
Code
HTML
<div align="center" style="user-select: none;">
<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>
JavaScript
<script>
let firstChecked = null;
let secondChecked = null;
document.querySelectorAll("input[type='checkbox']").forEach((checkbox) => {
checkbox.addEventListener("click", function (event) {
if (!firstChecked) {
firstChecked = event.target;
console.log("첫 번째 클릭:", firstChecked.id);
} else if (event.shiftKey) {
secondChecked = event.target;
console.log("두 번째 클릭:", secondChecked.id);
let checkboxes = document.querySelectorAll("input[type='checkbox']");
let start = [...checkboxes].indexOf(firstChecked);
let end = [...checkboxes].indexOf(secondChecked);
checkboxes.forEach((cb, index) => {
if (index > Math.min(start, end) && index < Math.max(start, end)) {
cb.checked = !cb.checked;
}
});
setTimeout(() => {
firstChecked = null;
secondChecked = null;
}, 100);
} else {
firstChecked = event.target;
secondChecked = null;
}
});
});
</script>