Marc Dupuis
Marc Dupuis

Reputation: 531

Specify the event you want

I have lots of checkboxes. Most of them have one class(class a or class b) but some of them have both classes.

<input type="checkbox" class="a b">

I have the same jquery event (change) for both of these classes.

$('.a').change(function(e){ // whatever });
$('.b').change(function(e){ // whatever });

In my code I have to trigger the event "change" from the input in a .each(). It means there can be checkboxes of any case stated above.

$(this).trigger('change');

My problem is that when I trigger it from a checkbox which has both classes, it triggers the 2 distinct event (and it's logic). But I just want to trigger the chosen change event of one class.

Is there a way to specify this ?

Upvotes: 1

Views: 51

Answers (2)

Fr&#233;d&#233;ric Hamidi
Fr&#233;d&#233;ric Hamidi

Reputation: 262939

You can fix your problem by filtering our the elements that expose both classes. For instance, only register the handler for class b if the element doesn't also expose class a:

$(".a").change(function(e) { /* whatever */ });
$(".b:not(.a)").change(function(e) { /* whatever */ });

Upvotes: 0

Anton
Anton

Reputation: 32581

Why not specify like this?

$('.a:not(".a.b")').change(function(){
//only a
});

$('.a.b').change(function(){
//both
});

$('.b:not(".a.b")').change(function(){
//only b    
});

Upvotes: 2

Related Questions