Greg Greg - 5 months ago 14
jQuery Question

Boostrap 3 active state button. How get total active button?

At page I have many button active state of type. I bind to the event click and check how many button have active status. But when I click at first button I get zero.

$(".btn-quote").on("click", function (e) {
var totalActiveQuote= $(".btn-quote.active").length;

if (totalActiveQuote > 0) {
console.log("active");
} else {
console.log("deactive");
}
});


What I should do to fix this?

jsfiddle.net

https://jsfiddle.net/haqkbvbh/

Answer

This is because the active class is toggled after your onClick event fires. You could fix it by toggling it on your own.

$(document).ready(function(){
  $(".btn-quote").on("mouseup", function (e) {
    $(this).toggleClass("myActive");
    var totalActiveQiote = $(".btn-quote.myActive").length;
    $("#totalActive").html(totalActiveQiote);
  });
});