Chris
Chris

Reputation: 27384

jQuery: Disable all checkboxes apart from current one

I have checkboxes that need to act in a similar fashion to radio button controls. Essentially when one is checked all others need to be unchecked. How can I achieve this with as little pain as possible?

So to summarise. If a checkbox is checked, all others (siblings) must then be unchecked leaving the clicked one checkstate untouched.

I already know how to uncheck all checkboxes but if I did this, I would have to first store the checked state of the checkbox that was checked, then reapply it after unchecking all checkboxes. I wondered if there was a way of doing this with some fancy jQuery selectors or some such.

Upvotes: 3

Views: 6750

Answers (4)

ThiefMaster
ThiefMaster

Reputation: 318468

By using radio buttons. Seriously, radio buttons are there for a reason. People expect radio buttons to be a "1 out of n" selection and checkboxes to be a "0 up to n" selection.

Anyway, here's the code:

$('input:checkbox').click(function() {
    $(this).siblings('input:checkbox').removeAttr('checked');
});

Demo: http://jsfiddle.net/ThiefMaster/AVEjt/

But please, only use it if you actually need to allow the user to uncheck everything. Then it's acceptable - otherwise radio buttons are much better.

Upvotes: 10

Wayne
Wayne

Reputation: 60414

As an alternative to ThiefMaster's very good answer you could register the event on the parent form and catch all checkboxes, including those nested in a fieldset (or some other element) that would be missed using "siblings".

$("#myform").click(function(e) {
    if ($(e.target).is("input:checkbox")) {
        $("input:checkbox", this).not(e.target).removeAttr("checked");
    }
})

Demo: http://jsfiddle.net/Gs3wa/

Upvotes: 0

Alnitak
Alnitak

Reputation: 339786

Try this:

$(':checkbox').not( selector_for_current ).attr('checked', false);

Where selector_for_current is the "current one", often this if you're in a callback.

Upvotes: 2

Try this:

$(function() {
    $("input[type=checkbox]").click(function(){
        $(this).siblings("input[type=checkbox]:not(this)").attr("checked", "");
    });
});

See example.

Upvotes: 0

Related Questions