I want to programmable switch tabs (using bootstrap 5). Bootsrap docs say:
As a best practice, we recommend using elements for the tabs, as these are controls that trigger a dynamic change, rather than links that navigate to a new page or location.
So I want use buttons instead links. Code:
$("#mybut").click(function() { var sel = document.querySelector('#nav-tab-manager') bootstrap.Tab.getInstance(sel).show() })
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"></script> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet"/> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <nav> <div class="nav nav-tabs" id="nav-tab" role="tablist"> <button class="nav-link active" id="nav-tabs-order" data-bs-toggle="tab" data-bs-target="#tabs-1" type="button" role="tab" aria-controls="tabs-1" aria-selected="true">Orders </button> <button class="nav-link" id="nav-tab-manager" data-bs-toggle="tab" data-bs-target="#tabs-2" type="button" role="tab" aria-controls="tabs-2" aria-selected="false">Managers </button> </div> </nav> <div class="tab-content" id="myTabContent"> <div class="tab-pane fade show active" id="tabs-1" role="tabpanel" aria-labelledby="tabs-tab1"> Orders </div> <div class="tab-pane fade" id="tabs-2" role="tabpanel" aria-labelledby="tabs-2"> Managers </div> </div> <button type="button" class="btn btn-primary" id="mybut">Want switch to manager</button>
Problem is wrong selector. But I have no idea why.
Advertisement
Answer
You’ll want to use getOrCreateInstance
instead because the Tabs aren’t being first initialized via JS.
$("#mybut").click(function() { var sel = document.querySelector('#nav-tab-manager') bootstrap.Tab.getOrCreateInstance(sel).show() })