javascriptjquerytwitter-bootstrap-3

How to toggle button in button-group on page load?


I've a button group like below

<div class="btn-group" data-toggle="buttons">
    <label class="btn btn-default">
        <input type="radio" name="environment" id="staging" value="staging" />Staging
    </label>
    <label class="btn btn-default">
        <input type="radio" name="environment" id="production" value="production" />Production
    </label>
</div>

I want to toggle to production on page load. I'm doing below to achieve this.

$(document).ready(function() {
   $("#production").button('toggle');
}

But nothing is happening. How should I do this ? Also, how do I know which button is active ?

I'm using Bootstrap 3.3.2 with Jquery 1.11.1


Solution

  • Button is represented by label. So all you need to do is to call button method on the parent label element:

    $(document).ready(function() {
        $("#production").parent().button('toggle');
    });
    

    Or much better, if you want to make production selected by default you should add class active in HTML in the first place:

    <div class="btn-group" data-toggle="buttons">
        <label class="btn btn-default">
            <input type="radio" name="environment" id="staging" value="staging" />Staging
        </label>
        <label class="btn btn-default active">
            <input type="radio" name="environment" id="production" value="production" />Production
        </label>
    </div>