Sometimes it’s just not worth arguing. Here is a super-quick & nasty solution to a request for mutually exclusive checkboxes: one or no checkboxes can be selected. I know, I know, radio selector, right? A second improved solution follows the quick & nasty one. Even the worst ideas can be improved upon!
In this post:
- Iteration 1
- Iteration 2
Required knowledge:
Iteration 1
Some HTML:
<fieldset> <label for="ResponseSaidCBY">Yes</label><input type="checkbox" id="ResponseSaidCBY" /> <label for="ResponseSaidCBN">No</label><input type="checkbox" id="ResponseSaidCBN" /> </fieldset>
and some JavaScript:
function clickYes() { if (document.getElementById("ResponseSaidCBN").checked) { document.getElementById("ResponseSaidCBN").checked = false; } } function clickNo() { if (document.getElementById("ResponseSaidCBY").checked) { document.getElementById("ResponseSaidCBY").checked = false; } } document.getElementById("ResponseSaidCBY").onchange = clickYes; document.getElementById("ResponseSaidCBN").onchange = clickNo;
See the Pen Mutually exclusive checkboxes by David Fox (@foxbeefly) on CodePen.
Iteration 2
This improved solution is based on a comment made on the Codepen for my original solution.
See the Pen Mutually exclusive checkboxes revisited by David Fox (@foxbeefly) on CodePen.