west54322 west54322 - 2 months ago 14
HTML Question

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!

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

Comments