Disable all unchecked checkboxes of a class in jquery

13,801

Solution 1

Try this:

$('.test').change(function(){
    if($('input.test').filter(':checked').length == 1)
        $('input.test:not(:checked)').attr('disabled', 'disabled');
    else
        $('input.test').removeAttr('disabled');
});​

JSFiddle

Solution 2

This subject has already been beaten to death. Consensus was use of radio buttons with a "none" option of some sort. This way you avoid coding new functionality into controls for which users hold certain expectations.

Share:
13,801
khagesh
Author by

khagesh

Updated on June 05, 2022

Comments

  • khagesh
    khagesh almost 2 years

    I want to disable all unchecked checkboxes of a class when one of the checkboxes in that class is checked so i tried this

    if ((($('input[type=checkbox]:checked.classname)).length)==1) {
    
        $('.classname').not(':checked').each(function(){
                            $(this).attr('disabled','disabled');
                            });
    

    and i also tried this one

        $("input[type=checkbox]."+aclass).not(':checked').attr('disabled',true);
    

    This code doesnt disable any of the checkboxes although i am getting the length right using this selector?

  • Aaron Fowler
    Aaron Fowler over 11 years
    While the accepted answer is technically correct, this is really the best answer.
  • Brock Hensley
    Brock Hensley almost 11 years
    I was overthinking this in the beginning of using checkboxes to choose between a list of items when only 1 can be chosen.... thank you for reminding me of the RADIO option! duhhhhh KISS