How to programmatically check a Bootstrap button group (radio) button
Asked Answered
S

3

12

http://jsfiddle.net/rphpbqp9/

<div class="btn-group" data-toggle="buttons">
    <label class="btn btn-sm btn-primary success active">
        <input type="radio" name="options" id="optionFalse" checked />false
    </label>
    <label class="btn btn-sm btn-primary danger">
        <input type="radio" name="options" id="optionTrue" />true
    </label>
</div>

$('#optionTrue').button('toggle');

I've read more question answers, but none of them works. The button toggle doesn't work, I tried to add/remove "active" class, doesn't have an effect. I'm using 1.10 jQuery and 3.1 Bootstrap. This supposed to be simple, I'm pulling my hair out!

Sheik answered 31/8, 2014 at 6:6 Comment(0)
B
24

button() needs to be called on the element with the class btn...

$('#optionTrue').closest('.btn').button('toggle');

This will toggle the buttons properly and update the checked properties of each input properly...

Fiddle

Boothman answered 31/8, 2014 at 6:34 Comment(3)
You are right sir! Should I maybe put the id to the label then, so I don't have to call 'closest'?Sheik
I wish I asked this question earlier, I'd have more hair left by now.Sheik
I just tried, it works if I move the ids a level up, then I don't have to use closest jsfiddle.net/6h3c5axn/1 , one more thing: the is checked calls don't work then. You can dig down for the child though to get to the input field.Sheik
P
3

It's crazy the bootstrap docs (3.2) don't make this more obvious, but here's the simplest method I've found to set the initial state of radio buttons in code.

<div class="btn-group" data-toggle="buttons">
    <label id="optionFalse" class="btn btn-primary">
        <input type="radio" name="options" /> false
    </label>
    <label id="optionTrue" class="btn btn-primary ">
        <input type="radio" name="options" /> true
    </label>
</div>

if (initTrue) {
    $('#optionTrue').button('toggle');
}
else {
    $('#optionFalse').button('toggle');
}

After reading dozens of posts on this subject, it seems these are the general points of confusion:

  • The 'toggle' method doesn't toggle between states (off->on->off) as one might expect, but rather just sets the referenced button to "on" and turns all the other buttons "off".
  • The id referenced needs to be on the 'label' and not the 'input'.
Pelerine answered 23/12, 2014 at 17:41 Comment(1)
The id is on the label? How freaky is that?Sheik
L
1

http://jsfiddle.net/y5qccerz/

document.querySelector(".btn-group input[id='optionTrue']").checked = true;
Leatri answered 14/1, 2015 at 20:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.