Reputation: 6448
I listen for 2 click events. First one fires when checkbox is checked:
$('#example').on('click', '.option', function(){
// Some logic
});
Second one fires when it's unchecked:
$('#example').on('click', '.checked.option', function(){
// Some other logic
});
As for HTML input element, I tried applying class to it in various ways:
class="checked option"
class="checked.option"
class="option checked"
class="option.checked"
But in either case, when checkbox is unchecked - both events get triggered instead of just second one.
QUESTION: Is there a way to prevent this? Or is there a more convenient way to detect click event on a checkbox AND that it was unchecked?
Thanks.
Upvotes: 0
Views: 87
Reputation: 491
QUESTION: Is there a way to prevent this? Or is there a more convenient way to detect click event on a checkbox AND that it was unchecked?
Yes, the code below should prevent it and I would use jQuery selectors (convenient imo) to detect this. Hope this helps! Thanks.
$('input:checkbox').click(function () {
if ($(this).is(":checked")) {
alert('was un-checked');
} else {
alert('was checked');
}
});
See the code work here:
Upvotes: 1
Reputation: 236122
You should really use the change
event instead of a click
and then check the button state.
$('#example').on('change', '.option', function() {
if( this.checked ) {
}
else {
}
});
Upvotes: 0
Reputation: 46060
A couple of ways:
$('#example').on('click', '.option', function(){
if ($(this).is(':checked')) ...
});
See the checked
selector http://api.jquery.com/checked-selector/
Or:
$('#example').on('click', '.option:not(.checked)', function(){
...
});
See the not
selector http://api.jquery.com/not-selector/
Or even:
$('#example').on('click', '.option:not(:checked)', function(){
...
});
$('#example').on('click', '.option:checked', function(){
...
});
Oh, and BTW, classes should be applied like: class="option checked"
, you should never put a .
in the class attribute.
Upvotes: 1