1

I have an issue with a click event on a bootstrap button group. I am attempting to retrieve the ids of the buttons that are active. Including the one I'm currently clicking on (if it was unselected). The issue is that the current button I'm clicking on doesn't get added as a selected button when I selected it. As if the class active hasn't been applied yet.

Here is my button group:

  <div class="btn-group" id = "rbtns" data-toggle="buttons-checkbox" >
        <button class="btn rbtn" id = "0">0</button>
        <button class="btn rbtn" id = "1">1</button>
        <button class="btn rbtn" id = "2">2</button>
        <button class="btn rbtn" id = "3">3</button>
        <button class="btn rbtn" id = "4">4</button>
  </div>

And my action:

 $( document ).ready(function() {

       $(".rbtn").click(function () {

        var data = [];

        $('#rbtns .btn.active').each(function() {
              data.push($(this).attr('id'));

        });

        alert ("Data length: " + data.length);
       });

How can I make sure I receive all ids the buttons with class active?

The buttons I am using are bootstrap checkbox style buttons. Once you click on them they are selected. And when you click on them they get unselected.

3 Answers 3

2

You could add the class in your click function before your retrieve all of the active buttons.

$(this).addClass('active');

Use the button method to set the checkbox before retrieving

$(this).button('toggle'); 

Here is a working example, however I dont really like call button('toggle') twice.

Sign up to request clarification or add additional context in comments.

Comments

0

Try explicitly setting the clicked button as active

$(".rbtn").click(function () {
  if ($(this).hasClass('active') == false){
    $(this).addClass('active');
  }

1 Comment

setting explicitly seems to remove the toggle behavior of the button. It doesn't stick When you click on it.
0

Fiddle: http://jsfiddle.net/xdyRt/

$(".rbtn").click(function () {
    $(this).toggleClass("active");     
    var data = [];

    $(".btn").each(function() {
        $(this).hasClass("active") ? data.push($(this).attr("id")) : null;
    });

    for (var i = 0; i < data.length; i++) {
        alert(data[i]);
    }
});

3 Comments

This doesn't keep the button selected once I click on it. It doesn't work as a toggle button anymore.
Check it now, added a fiddle
This doesn't seem to do it. Maybe because I an using checkbox style buttons as in the link I added in the description in the checkbox session. Maybe the bootstrap js toggles the button after the jquery code is ran so it toggles it back

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.