jQuery – checkboxes like radiobuttons

Here’s a hint: Use radio buttons. 😉

I wouldn’t recommend doing this because it would be considered bad for usability and would certainly violate the principle of least surprise. Users have been conditioned to expect radios to accept 1 check and checkboxes to accept many. Don’t make your users think.

If you have your reasons, though, here’s how to go about doing this with jQuery:

<input type="checkbox" name="mygroup1" value="1" class="unique">
<input type="checkbox" name="mygroup2" value="2" class="unique">
<input type="checkbox" name="mygroup3" value="3" class="unique">

And the jQuery:

var $unique = $('input.unique');
$unique.click(function() {
    $unique.filter(':checked').not(this).removeAttr('checked');
});

And here’s a live sample.

EDIT:

As pointed out in the comments, this would allow the user to deselect all checkboxes even if they chose one initially, which isn’t exactly like radio buttons. If you want this, then the jQuery would look like this:

var $unique = $('input.unique');
$unique.click(function() {
    $unique.removeAttr('checked');
    $(this).attr('checked', true);
});

Leave a Comment