janeh
janeh

Reputation: 3804

Don't trigger JQuery on a disabled checkbox

I have a form with checkboxes. When users click on label, I have custom checkbox icon that gets swapped. That works fine, but I also have disabled checkboxes in the form, and I don't wan't the click event to be triggered when you click on the disabled ones. How do I do that?

JQuery:

$('input[type=checkbox] + label').click(function() {
  $(this).toggleClass('checkbox-pressed');
});

HTML:

<input type="checkbox" id="A"><label for="A">Option 1</label>
<input disabled type="checkbox" id="B"><label for="B">Option 2 - don't trigger JQ</label>

Upvotes: 0

Views: 208

Answers (3)

palaѕн
palaѕн

Reputation: 73906

You can use the :enabled selector like this:

$(':checkbox:enabled').click(function() {
    // Your code here...
});

Upvotes: 3

achudars
achudars

Reputation: 1506

it would be easier to use :checked in jQuery

you can find more here.

Upvotes: 0

techfoobar
techfoobar

Reputation: 66663

Use :not(:disabled) to select only those checkboxes that aren't disabled.

$('input[type=checkbox]:not(:disabled)').click(function() {
    ...
});

Documentation: :not() and :disabled


You should rather use .on(). Otherwise it won't work for checkboxes that become disabled after the page loads up initially (say, because of some user action):

$(document).on('click', 'input[type=checkbox]:not(:disabled)', function() {
    ...
});

Upvotes: 6

Related Questions