Skip to content
Advertisement

How to change active bootstrap tab with javascript

I have tried to change the active tab and failed to use the javascript onclick element correctly. Here’s the code:

<ul class="nav nav-tabs" style="text-align: left;">
    <li class="active"><a href="#first" data-toggle="tab">First</a></li>
    <li><a href="#second" data-toggle="tab">Second</a></li>
    <li><a href="#third" data-toggle="tab">Third</a></li>
</ul>

<div class=“tab-content">

<div id="first" class="tab-pane fade in active">
Text

<a href="#second" class="btn btn-primary btn-lg" onclick="CHANGE ACTIVE TAB TO SECOND" data-toggle="tab">Second</a>

<a href="#third" class="btn btn-primary btn-lg" onclick="CHANGE ACTIVE TAB TO THIRD" data-toggle="tab">Third</a>

</div>


<div id="second" class="tab-pane fade in">
Text
</div>


<div id="third" class="tab-pane fade in">
Text
</div>


</div>

How could I be able to use the buttons to change the active tab to their associated id? Please advise.

Have a great day!

Advertisement

Answer

You can trigger click on tab you want when click on your buttons

<ul class="nav nav-tabs" style="text-align: left;">
    <li class="active"><a href="#first" data-toggle="tab" id="first_tab">First</a></li>
    <li><a href="#second" data-toggle="tab" id="second_tab">Second</a></li>
    <li><a href="#third" data-toggle="tab" id="third_tab">Third</a></li>
</ul>

<div class="tab-content">        
    <div id="first" class="tab-pane fade in active">
        Text        
        <a class="btn btn-primary btn-lg" onclick="$('#second_tab').trigger('click')">Second</a>        
        <a class="btn btn-primary btn-lg" onclick="$('#third_tab').trigger('click')">Third</a>        
    </div>
    ....
</div>

here is a Demo

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement