Christian Caspovich
Christian Caspovich

Reputation: 169

Bootstrap button checkboxes

$('label > input[type=checkbox]').on('change', function () {
    var selected = 0;
    $('label.active').each(function () {
        selected++;
    });
    console.log(selected);
});

I use this code for when one of the bootstrap checkbox buttons change, but when I log it to the console, it isn't accurate, like

change() -> 1 active button -> console shows 0

change() -> 2 active buttons -> console shows 1

change() -> 3 active buttons -> console shows 2

change() -> 4 active buttons -> console shows 3 etc

EDIT My question was maybe a bit misleading, inside the each I have a function I want to execute on the ekements that are active

I was just counting to see if I could find all the selected elements

$('label.active').each(function () {
     // Active, so do a function
     myfunc();
}); 

Thanks.

Upvotes: 1

Views: 198

Answers (2)

Ted
Ted

Reputation: 14927

I would guess the active class is added to the label on change as well, meaning it can happen after your code executes.

Edited per OP's edit try

   $('label > input[type=checkbox]').on('change', function () {
        var selected = 0;
        $('label > input[type="checkbox"]:checked').each(function(index, element){
             selected++; 
             //in case you need these element:
             var $cb = $(element), //the checkbox
                 $label = $cb.parent('label'); //the checkboxs label

             //your code here

        });
        console.log(selected);
    });

Upvotes: 1

howderek
howderek

Reputation: 2244

Try this:

$('label > input[type=checkbox]').on('change', function () {
    var selected = $('label.active').length;
    console.log(selected);
});

Just get the length of the array and make that the total number selected.

Upvotes: 0

Related Questions