checkbox

Sometimes it’s just not worth arguing.

Super quick and nasty solution to a request for checkboxes that are mutually exclusive: one or no checkboxes can be selected. I know, I know; radio selector, right?

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.0

By foxbeefly

PHP / MySQL Developer

Leave a Reply

Your email address will not be published. Required fields are marked *

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