Homer_J
Homer_J

Reputation: 3323

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"));
});

Upvotes: 8

Views: 17556

Answers (3)

azadeh noorzad
azadeh noorzad

Reputation: 20

jQuery - checkbox enable/disable

this source check all checkbox :

$("input:checkbox").each(function(){
  var $this = $(this);
  if($this.is(":checked")){
       alert('enable');
  }
});

Upvotes: 0

billyonecan
billyonecan

Reputation: 20260

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

Upvotes: 23

Kristof Feys
Kristof Feys

Reputation: 1842

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).

Upvotes: 2

Related Questions