0

I have got this group of checkboxes that behave like radio buttons.

I need some help in letting the user allow to uncheck a checkbox too, so there can be no selection within the group.

<label><input type="checkbox" name="cb1" class="chb" /> CheckBox1</label>
<label><input type="checkbox" name="cb2" class="chb" /> CheckBox2</label>
<label><input type="checkbox" name="cb3" class="chb" /> CheckBox3</label>
<label><input type="checkbox" name="cb4" class="chb" /> CheckBox4</label>


$(".chb").each(function()
           {
               $(this).change(function()
                              {
                                  $(".chb").attr('checked',false);
                                  $(this).attr('checked',true);
                              });
           });
2
  • 1
    I don't understand what are you trying to achieve. if you are allowing only one option, have you consider using a drop down list instead? Commented Sep 26, 2011 at 3:47
  • 1
    ...or radio buttons with a "None" option? Commented Sep 26, 2011 at 3:48

1 Answer 1

3
$(".chb").change(function()
{
    $(".chb").parent().siblings()
        .find('input').prop('checked', false);
});

Or even better:

var $inputs = $(".chb");

$inputs.change(function()
{
    $inputs.not(this).prop('checked', false);
});

And here's the fiddle: http://jsfiddle.net/zjJKc/

Sign up to request clarification or add additional context in comments.

5 Comments

@Christian - What do you mean by "radio button behavior"? I thought you meant that only one of them can be checked, so that when you check one of them, all the others get unchecked. This is how my code works. If that's not what you meant, please explain what you mean by "radio button behavior".
the fiddle works. It does not work with my mark up because the checkboxes are in seperate html elements and not in one single group. when I implement it fiebug tells me "$inputs.not(this).prop('checked', false); " is not a function
@Christian - Which version of jQuery are you using? .prop was introduced in version 1.6, so if you're using anything below that, use .attr.
@Christian - Since you haven't provided your full markup, there's no way for me to guide you on how to select all those checkboxes together into the $inputs variable...
thanks I was using 1.4. I upgraded to 1.6 and that fixed it. thanks for the valuable info and snippet ;-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.