Select any combination whose total value does not exceed 10. If a new selection would make the sum larger than 10, that selection is undone.
const boxes = [...document.querySelectorAll('input[name="ckb"]')];
const maximum = 10;
function currentSum() {
return boxes
.filter((box) => box.checked)
.reduce((sum, box) => sum + Number(box.value), 0);
}
boxes.forEach((box) => {
box.addEventListener("change", () => {
if (currentSum() > maximum) {
box.checked = false;
}
});
});
<label><input type="checkbox" name="ckb" value="1"> Value = 1</label>
<label><input type="checkbox" name="ckb" value="2"> Value = 2</label>
<label><input type="checkbox" name="ckb" value="3"> Value = 3</label>
<div id="msg" aria-live="polite">Sum: 0</div>
Checkbox limit tutorial Count-limit demo
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.