Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery check only enabled checkboxes

My checkboxes:

<input disabled="disabled" class="Spec" type="checkbox" value="1" />
<input class="Spec" type="checkbox" value="2" />
<input disabled="disabled" class="Spec" type="checkbox" value="5" /> 
<input class="Spec" type="checkbox" value="8" /> 
<input disabled="disabled" class="Spec" type="checkbox" value="10" />  
<input class="Spec" type="checkbox" value="30" />

My jQuery selects all the checkboxes regardless of whether they are enabled or disabled - is it possible to only check those that are enabled?

$('#Spec_all').on('click', function() {
    $('.Spec').attr('checked', $(this).is(":checked"));
});
like image 344
Homer_J Avatar asked Nov 06 '13 08:11

Homer_J


2 Answers

You can use the :enabled pseudo selector:

$('.Spec:enabled:checked')

So select all elements with the class Spec, which are not disabled, and are checked.

edit

You don't want to select checked checkboxes in your selector, otherwise once they're unchecked, they won't be selected again. You can do the following:

$('#Spec_all').on('click', function() {
   $('.Spec:enabled').prop('checked', this.checked);
});

Here's a fiddle

like image 86
billyonecan Avatar answered Nov 06 '22 04:11

billyonecan


Selecting the checked checkboxes is rather easy. All you need to do is define the class and use the checked selector. This results in something like this:

 $('.Spec:checkbox:checked:enabled')

cfr: http://api.jquery.com/checked-selector/

to select only the enabled ones... add the enabled selector (http://api.jquery.com/enabled-selector/)

you could also use :not(:disabled) instead of enabled. There is a slight difference (explained in the enabled-selector documentation) I've also added the "checkbox" selector in order to make sure that we're only checking checkboxes (if it could be the case that .Spec is also used for other types).

like image 40
Kristof Feys Avatar answered Nov 06 '22 06:11

Kristof Feys