8

I've been trying to use a button group (as per the instructions at at http://getbootstrap.com/javascript/#buttons) and then to parse their values into a shifted array:

Code for the btn-group

<div class="btn-group" id="weekdays" data-toggle="buttons">
    <label class="btn btn-default">
      <input type="checkbox" >Mo
    </label>
    <label class="btn btn-default">
      <input type="checkbox">Tu
    </label>
    <label class="btn btn-default">
      <input type="checkbox">We
    </label>
  </div>
</div>

Code for reading the values

$("#weekdays ").change(function(event){

   var checkedDays = $("#weekdays :checkbox").map(function(){
        return $(this).is(':checked') ? 1 : 0;
    }).get(); // <----

    var sun = checkedDays.pop();

    checkedDays.unshift(sun);

    console.log(checkedDays);
});

So far so good. (Even if I'm sure the code could be better written.)

However, my problem comes when I try to set the values of the checkboxes programatically, and get it reflected in the UI. I've sort of managed to change the values of the checkboxes using a number of methods $(this).prop('checked', true), etc, which seems to update the backing values, but it does nothing to change the appearance of the buttons.

I've seen a number of solutions, but none that works with the Bootstrap 3.0 recommended way of setting up the checkbox btn-group. Does anyone have a solution?

0

2 Answers 2

11

If you use a DOM editor when clicking on the Bootstrap buttons, you'll see that a class active is added to the label (not the checkbox input) when the button is clicked.

To programmatically toggle the buttons, use the Bootstrap .button('toggle') method on the label:

$('#weekdays label').eq(n).button('toggle');

http://jsfiddle.net/mblase75/4NVvj/

This will change both the appearance of the button and the checked property of the checkbox within.

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

Comments

6

In a similar case what worked for me was this:

$('#checkBoxId').trigger("click");

Which does exactly what you want.

PS. Not sure if it is the best but it worked for me back then.

1 Comment

I cannot seem to get this to work, but thanks for your answer!

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.