checkboxcheckbox

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

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.

By MisterFoxOnline

Mister Fox AKA @MisterFoxOnline is an ICT, IT and CAT Teacher. He has a passion for technology and loves to find solutions to problems using the skills he has learned in the course of his IT career.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.