nanonerd
nanonerd

Reputation: 1984

navigate bootstrap tab using jquery

I am using bootstrap Tabs. It works well.

<ul class="nav nav-tabs">
    <li class="nav active" id="li_All"><a href="#All" data-toggle="tab">All Exchanges</a></li>
    <li class="nav" id="li_Beginner"><a href="#Beginner" data-toggle="tab">Beginner</a></li>        
    <li class="nav" id="li_AddExchange"><a href="#AddExchange" data-toggle="tab" style="color:black; font-weight:600" >ADD EXCHANGE</a></li>
</ul>

When the page opens, sometimes I would like to pass in a value for "tabActive" that is "AddExchange". How to I navigate/show the #AddExchange tab instead of the default "#All" tab? Conceptually, I am trying to use window.location.replace below, but it is not working.

if (tabActive) {
    switch (tabActive) {
        case "Beginner":
            $("#li_All").removeClass("active");
            $("#li_Beginner").addClass("active");
            $("#li_AddExchange").removeClass("active");
            break;
        case "AddExchange":
            $("#li_All").removeClass("active");
            $("#li_Beginner").removeClass("active");
            $("#li_AddExchange").addClass("active");
            //location.href = "#AddExchange";
            window.location.replace("#AddExchange");
            break;
}

Upvotes: 0

Views: 733

Answers (2)

Diego Alves
Diego Alves

Reputation: 2677

In the controller you set the tab you want selected based on your condition:

  //some conditions
  ViewBag.SelectedTab = "li_AddExchange";

Razor View, you grab the ViewBag value

 <input id="hiddenSelectedTab" type="hidden" value="@ViewBag.SelectedTab"/>

Using javascript you get the value that you just set to the hidden input and use it as a selector to the tab method.

<script>
    $().ready(function(){
       var selectedTab = $('#hiddenSelectedTab').val();
       $('#' + selectedTab + ' a:first').tab('show');
      });
</script>

To use tabs you need bootstrap javascript file imported after jquery.

Upvotes: 0

lscmaro
lscmaro

Reputation: 1065

You could just use the bootstrap method .tab('show') for this.

However you obtain your values for the variable tabActive is up to you. From there you can just do your if statement and use the method provided with the library, like so:

//We will assume tabActive = 'AddExchange' here
if (tabActive !== undefined){
   //This should open the #li_AddExchange tab on page load. 
   //IF that is actually the ID of your tabs' navigation
   $('#li_'+tabActive +' a').tab('show');
}

That should override your default active tab and select the dynamic one. Here is a simple fiddle example using the method. Notice that the shown tab is not the default active one. https://jsfiddle.net/ommhdm4o/2/

Upvotes: 1

Related Questions