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!

Cœur
  • 37,241
  • 25
  • 195
  • 267
Csaba Toth
  • 10,021
  • 5
  • 75
  • 121

3 Answers3

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

Anthony Chu
  • 37,170
  • 10
  • 81
  • 71
  • You are right sir! Should I maybe put the id to the label then, so I don't have to call 'closest'? – Csaba Toth Aug 31 '14 at 06:43
  • 1
    I wish I asked this question earlier, I'd have more hair left by now. – Csaba Toth Aug 31 '14 at 06:44
  • I just tried, it works if I move the ids a level up, then I don't have to use closest http://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. – Csaba Toth Aug 31 '14 at 06:46
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'.
Jay Borseth
  • 1,894
  • 20
  • 29
1

http://jsfiddle.net/y5qccerz/

document.querySelector(".btn-group input[id='optionTrue']").checked = true;
Hugolpz
  • 17,296
  • 26
  • 100
  • 187