Nick Ginanto
Nick Ginanto

Reputation: 32120

jQuery - hasClass of a button works with delay

I am using bootstrap checkbox button to have a button group. When a user clicks on one of the buttons, it becomes active.

I use the function below to check which button is active and which is not and then use this data in the rest of the function.

as you can see in the jsfiddle, the results are delayed, and it would be correct if I would change is to was. But I need the test in the function I'm using, not on the next call to the function.

Can someone explain to me why this happen and if my hasClass check is correct for this kind of situation?

HTML:

<div class="box btn-group" data-toggle="buttons-checkbox">
    <button data-filter="a" id="a" name="button" type="button" class="btn">A</button>
    <button data-filter="b" id="b" name="button" type="button" class="btn">B</button>
</div>​

CSS:

$(".box").on('click', function(){
    alert("a is " + ($("#a").hasClass("active") ? "active" : "not-active"));
    alert("b is " + ($("#b").hasClass("active") ? "active" : "not-active"));
});​

jsfiddle

Upvotes: 1

Views: 1420

Answers (1)

Alexander
Alexander

Reputation: 23537

Twitter Bootstrap automatic bindings works at document level, which means that your click event at .box level still doesn't know about the change of state of the buttons.

You can drop the automatic binding removing the data-toggle attribute for this group of checkboxes and use .button() as documented in the Twitter Bootstrap API.

<div class="box btn-group">
    <button data-filter="a" id="a" name="button" type="button" class="btn">A</button>
    <button data-filter="b" id="b" name="button" type="button" class="btn">B</button>
</div>​

$(".box").on('click', '.btn', function(){
    $(this).button("toggle");    
    alert("a is " + ($("#a").hasClass("active") ? "active" : "not active"));
    alert("b is " + ($("#b").hasClass("active") ? "active" : "not active"));
});

See it here.

Upvotes: 2

Related Questions