8

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"));
});
tshepang
  • 12,111
  • 21
  • 91
  • 136
Homer_J
  • 3,277
  • 12
  • 45
  • 65

3 Answers3

23

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

billyonecan
  • 20,090
  • 8
  • 42
  • 64
2

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

Kristof Feys
  • 1,822
  • 1
  • 19
  • 36
  • Not sure that is correct - I need to select the 'enabled' checkboxes only. – Homer_J Nov 06 '13 at 08:35
  • Thanks Kristof - I must be going wrong with my code: `$('.Spec:checkbox:checked:enabled').attr('checked', $(this).is(":checked"));` Whilst it doesn't check the disabled boxes, neither does it check the enabled ones :-( – Homer_J Nov 06 '13 at 08:42
  • `:enabled` only selects the checkboxes which are explicitly set to enabled. If this isn't the case, you should use `:not(:disabled)` – Kristof Feys Nov 06 '13 at 08:44
0

jQuery - checkbox enable/disable

this source check all checkbox :

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