Wednesday, September 3, 2008

Mutually exclusive checkboxes with jQuery

I was needing a way for the user to select none or just one item in a set... here is how I've managed to achieve this functionality using jQuery:

<html>
<
head>
<
script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<
script type="text/javascript" language="javascript">
$(document).ready(function() {
$('.mutuallyexclusive').click(function () {
checkedState = $(this).attr('checked');
$('.mutuallyexclusive:checked').each(function () {
$(this).attr('checked', false);
});
$(this).attr('checked', checkedState);
});
});
</script>
</
head>
<
body>
<
div>
Red: <input id="chkRed" name="chkRed" type="checkbox" value="red" class="mutuallyexclusive">
Blue: <input id="chkBlue" name="chkBlue" type="checkbox" value="blue" class="mutuallyexclusive">
Green: <input id="chkGreen" name="chkGreen" type="checkbox" value="green" class="mutuallyexclusive">
</
div>
</
body>
</
html>

A running sample is here. (Dead link)

(Based on this post. Thanks Tony.)

Submit this story to DotNetKicks

3 comments:

Alex said...

Thanks, this was really helpful.

Rejish Khan M said...

Thansk for the excellent solution. Since ASP.NET puts a span tag around CheckBox and applies the class to that span, i'd to slightly modify the code as below:

$(document).ready(function() {
$('.mutuallyexclusive input').click(function () {
checkedState = $(this).attr('checked');
$('.mutuallyexclusive input:checked').each(function () {
$(this).attr('checked', false);
});
$(this).attr('checked', checkedState);
});
});

Germán Schuager said...

You are welcome.
That's one good thing about MVC compared to WebForms.... I get to choose my markup and not ASP.NET :)