CodeVirtuoso
CodeVirtuoso

Reputation: 6448

jQuery - how to prevent click event on merged classes to also be interpreted as click event on a single class?

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

Answers (3)

Clint
Clint

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:

http://jsfiddle.net/SCSZ6/

Upvotes: 1

jAndy
jAndy

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

Petah
Petah

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

Related Questions