Javascript Limit Selected Checkboxes To 2
I would like to disable selecting more than 2 choice checkboxes, but I couldn't do it with my javascript code. How can I do this? btn.addEventListener('click',function () { var our
Solution 1:
You could probably use this logic to prevent more than one checkbox being selected:
- Check the total number of checked select boxes.
- If the total number exceeds the max number, disable the check.
Code:
<label><inputtype="checkbox"class="check" /> Checkbox 1</label><label><inputtype="checkbox"class="check" /> Checkbox 2</label><label><inputtype="checkbox"class="check" /> Checkbox 3</label><label><inputtype="checkbox"class="check" /> Checkbox 4</label><label><inputtype="checkbox"class="check" /> Checkbox 5</label>
And the JavaScript for the same.
var checks = document.querySelectorAll(".check");
var max = 2;
for (var i = 0; i < checks.length; i++)
checks[i].onclick = selectiveCheck;
functionselectiveCheck (event) {
var checkedChecks = document.querySelectorAll(".check:checked");
if (checkedChecks.length >= max + 1)
returnfalse;
}
Snippet
var checks = document.querySelectorAll(".check");
var max = 2;
for (var i = 0; i < checks.length; i++)
checks[i].onclick = selectiveCheck;
functionselectiveCheck (event) {
var checkedChecks = document.querySelectorAll(".check:checked");
if (checkedChecks.length >= max + 1)
returnfalse;
}
<label><inputtype="checkbox"class="check" /> Checkbox 1</label><label><inputtype="checkbox"class="check" /> Checkbox 2</label><label><inputtype="checkbox"class="check" /> Checkbox 3</label><label><inputtype="checkbox"class="check" /> Checkbox 4</label><label><inputtype="checkbox"class="check" /> Checkbox 5</label>
Post a Comment for "Javascript Limit Selected Checkboxes To 2"