How to programmatically check a Bootstrap button group (radio) button
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'.
http://jsfiddle.net/y5qccerz/
document.querySelector(".btn-group input[id='optionTrue']").checked = true;
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