How to open specific tab of bootstrap nav tabs on click of a particuler link using jQuery?
Asked Answered
S

9

83

I am new to jquery and bootstrap,so please consider my mistakes.I have created a bootstrap modal for login and registration. It contains two nav-tabs called as login and registration.I have two buttons that popup the same Modal window, but display a different tab inside the Modal window. In each tab is a form with a number of inputs. My issue is getting the modal popped up with login tab opened in the modal when i click on the 'login' button and registration tab opened when i click on the 'register' button on my page.

These are 2 links on which the modal opens:

<div class="header-login-li" style="background-color:gray;float:left;width:100px;height:60px;">
<a data-toggle="modal" href="#regestration" class="header-register-a" >
<big>
<font color="white" class="header-register-font"><center style="margin-top:20px;">Login <i class="icon-chevron-down" style="font-size:20px"></i></center></font>
</big></a></div>

<div class="header-register-li" style="background-color:green;float:right;margin-right:-15px;width:130px;height:60px;">
<a data-toggle="modal" href="#regestration" class="header-register-a" >
<big>
<font color="white" class="header-register-font"><center style="margin-top:20px;">Register</center></font>
</big></a>

Here is my code of tabs and their contents(i am avoiding unnecessary code here):

 <div class="tabbable" >
      <ul class="nav nav-tabs" ><!--tabs-->
        <li class="active" style="position:absolute;margin-left:0px;" id="logintab">
        <a href="#pane_login" data-toggle="tab">Login</a></li>
        <li style="margin-left:70px;" id="reg_tab" ><a href="#pane_reg" data-toggle="tab">Registration</a></li>

      </ul>
      <div class="tab-content"><!--login tab content-->
         <div id="pane_login" class="tab-pane active">
             <form id="login-form" target="login-signup-iframe" method="post" action="#" name="login-form">

              </form>

        </div><!--/pane_login-->

        <div id="pane_reg" class="tab-pane"><!--registration tab content-->
           <form id="regestration-form" target="login-signup-iframe" method="post" action="#" name="regestration-form">

            </form>
         </div>
        </div><!-- /.tab-content -->
</div><!-- /.tabbable -->

I think this can be done through jquery easily.But i dont know exactly how to do it. So,please can anyone help me to solve my problem.Thank you in advance ?

Stela answered 25/10, 2013 at 11:50 Comment(0)
S
169

Applying a selector from the .nav-tabs seems to be working

HTML is

<ul class="nav nav-tabs">
    <li><a href="#aaa" data-toggle="tab">AAA</a></li>
    <li><a href="#bbb" data-toggle="tab">BBB</a></li>
    <li><a href="#ccc" data-toggle="tab">CCC</a></li>
</ul>
<div class="tab-content" id="tabs">
    <div class="tab-pane" id="aaa">...Content...</div>
    <div class="tab-pane" id="bbb">...Content...</div>
    <div class="tab-pane" id="ccc">...Content...</div>
</div>

Script is

$(document).ready(function(){
  activaTab('aaa');
});

function activaTab(tab){
  $('.nav-tabs a[href="#' + tab + '"]').tab('show');
};

http://jsfiddle.net/pThn6/80/

Sidhu answered 25/10, 2013 at 11:53 Comment(5)
The tab-pane id is unnecessary and modifying the href feels weird to me. A cleaner solution would be to add an id to each tab: then you can change the long selector to something as simple as $('#' + tab).tab('show');Sternberg
@Skippr If you remove the tab-pane ids, how is each nav-tabs anchor linked to its tab-pane?Unsheathe
To summarize what's going on here: .tab('show') is being called on the <a> of the nav-tabs <li>Contextual
I tried that solution but it's not working for me. I'm using nav-pills instead of nav-tabs. Here is what I tried jsfiddle.net/Lumyc4gs/1 Can someone please help me to make it work? I'm using angularJs in my application, so may be even simpler solution?Deland
Never mind, got it to work by combining a few solutions from this thread jsfiddle.net/Lumyc4gs/2Deland
G
16

HTML:

<a href="PageName.php#tabID">link to other page tab</a>

Javascript:

window.onload = function(){  

    var url = document.location.toString();
    if (url.match('#')) {
        $('.nav-tabs a[href="#' + url.split('#')[1] + '"]').tab('show');
    }

    //Change hash for page-reload
    $('.nav-tabs a[href="#' + url.split('#')[1] + '"]').on('shown', function (e) {
        window.location.hash = e.target.hash;
    }); 
} 
Geophagy answered 4/2, 2015 at 8:44 Comment(4)
the id must be between quotations marks : $('.nav-tabs a[href="#' + url.split('#')[1] + '"]').tab('show');Heracliteanism
what's wrong with location.hash for also reading the hash in the first place?Upheaval
@Upheaval yes I don't understand why you would need to update it for a page-reloadWestberg
@Westberg that's so that you can bookmark the URL including the hash and automatically have the correct tab opened when you visit it.Upheaval
G
11

You may access through tab Id as well, But that id is unique for same page. Here is an example for same

$('#product_detail').tab('show');

In above example #product_details is nav tab id

Gader answered 13/9, 2016 at 4:36 Comment(1)
OR, if you are using HREF $('.nav-tabs a[href="#home"]').tab('show')Swords
A
7

Hi Try this one folks!

$('a[data-toggle="tab"]').on('shown.bs.tab', function(e) {
  // save current clicked tab in local storage does not work in Stacksnippets
  // localStorage.setItem('lastActiveTab', $(this).attr('href'));
});
//get last active tab from local storage
var lastTab = "#profile"; // localStorage.getItem('lastActiveTab');
console.log(lastTab + "tab was last active")
if (lastTab) {
  $('[href="' + lastTab + '"]').tab('show');
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>

<div class="container">
  <div>
    <!-- Nav tabs -->
    <ul class="nav nav-tabs" role="tablist">
      <li role="presentation" class="active"><a href="#home" aria-controls="home" role="tab" data-toggle="tab">Home</a></li>
      <li role="presentation"><a href="#profile" aria-controls="profile" role="tab" data-toggle="tab">Profile</a></li>
      <li role="presentation"><a href="#messages" aria-controls="messages" role="tab" data-toggle="tab">Messages</a></li>
      <li role="presentation"><a href="#settings" aria-controls="settings" role="tab" data-toggle="tab">Settings</a></li>
    </ul>

    <!-- Tab panes -->
    <div class="tab-content">
      <div role="tabpanel" class="tab-pane active" id="home">Home</div>
      <div role="tabpanel" class="tab-pane" id="profile">Profile</div>
      <div role="tabpanel" class="tab-pane" id="messages">Message</div>
      <div role="tabpanel" class="tab-pane" id="settings">Settings</div>
    </div>

  </div>
</div>
Auden answered 15/2, 2017 at 6:3 Comment(0)
S
4

Thanks for above answer , here is my jQuery code that is working now:

      $(".header-login-li").click(function(){
        activaTab('pane_login');                
      });

      $(".header-register-li").click(function(){
        activaTab('pane_reg');
        $("#reg_log_modal_header_text").css()
      });

      function activaTab(tab){
        $('.nav-tabs a[href="#' + tab + '"]').tab('show');
      };
Stela answered 25/10, 2013 at 12:33 Comment(0)
L
1
    function updateURL(url_params) {
        if (history.pushState) {
        var newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + '?' + url_params;
        window.history.replaceState({path:newurl},'',newurl);
        }
    }

    function setActiveTab(tab) {
        $('.nav-tabs li').removeClass('active');
        $('.tab-content .tab-pane').removeClass('active');

        $('a[href="#tab-' + tab + '"]').closest('li').addClass('active');
        $('#tab-' + tab).addClass('active');
    }

    // Set active tab
    $url_params = new URLSearchParams(window.location.search);


    // Get active tab and remember it
    $('a[data-toggle="tab"]')
        .on('click', function() {
        $href = $(this).attr('href')
        $active_tab = $href.replace('#tab-', '');

        $url_params.set('tab', $active_tab);
        updateURL($url_params.toString());
    });

    if ($url_params.has('tab')) {
        $tab = $url_params.get('tab');
        $tab = '#tab-' + $tab;
        $myTab = JSON.stringify($tab);
        $thisTab = $('.nav-tabs a[href=' + $myTab  +']');
        $('.nav-tabs a[href=' + $myTab  +']').tab('show');
    }
Lutenist answered 1/5, 2017 at 20:44 Comment(0)
R
0

May I suggest a php+css solution I used on my site? It's simple and no js problems :)

url to page: <a href="page.php?tab=menu1">link to menu1</a>

<?
$tab = $_GET['tab'];
?>
<ul class="nav nav-tabs">
  <li class="<? if ($tab=='menu1' OR $tab=='menu2') 
{
echo "";
} 
else {
echo "active";
}
?>"><a data-toggle="tab" href="#home">Prodotti</a></li>
  <li class="<? if ($tab=='menu1') 
{
echo "active";
} 
?>"><a data-toggle="tab" href="#menu1">News</a></li>
  <li class="<? if ($tab=='menu2') 
{
echo "active";
} 
?>"><a data-toggle="tab" href="#menu2">Gallery</a></li>
</ul>

<div class="tab-content">
  <div id="home" class="tab-pane fade <? if ($tab=='menu1' OR $tab=='menu2') 
{
echo "";
} 
else {
echo "in active";
}
?>
">
    <h3>Prodotti</h3>
    <p>Contenuto della pagina, zona prodotti</p>
  </div>
  <div id="menu1" class="tab-pane fade <? if ($tab=='menu1') 
{
echo "in active";
} 
?>">
    <h3>News</h3>
    <p>Qui ci saranno le news.</p>
  </div>
  <div id="menu2" class="tab-pane fade <? if ($tab=='menu2') 
{
echo "in active";
} 
?>">
    <h3>Gallery</h3>
    <p>Qui ci sarà la gallery</p>
  </div>
</div>
Reasoned answered 9/6, 2015 at 11:40 Comment(1)
You may definitely not suggest this. This is a very ill way of doing what he/she has asked.Immaculate
A
0

I wrote this snippet, that I've been using for handling this exact case.

It's in plain javascript, making it also suitable in cases like with bootsrap5 without jQuery.

<script type='text/javascript'>
    window.onhashchange=hashTriggerTab;
    window.onload=hashTriggerTab;
    
    function hashTriggerTab(){
        var current_hash=window.location.hash;
        if(current_hash.substring(0,1)=='#')current_hash=current_hash.substring(1);
        if(current_hash!=''){
            var trigger=document.querySelector('.nav-tabs a[href="#'+current_hash+'"]');
            if(trigger)trigger.click();
        }
    }
</script>

With that in place, you could link both on the same page, like:

<a href='#tabId'>Link Any Tab</a>

Or from external page like:

<a href='newpage.php#tabId'>Link From External</a>
Ambrosia answered 11/12, 2020 at 9:38 Comment(0)
R
-1

Not sure if I understood correctly but here is snippet that I use to open links from Bootstrap tab menu:

HTML

<ul class="nav nav-tabs">
  <li class="active"><a href="#foo" data-toggle="tab">Foo</a></li>
  <li><a href="#bar" data-toggle="tab">Bar</a></li>
  <li><a href="baz.html" class="external">Baz</a></li>
</ul>

<div class="tab-content">
  <div class="tab-pane active" id="foo">Foo</div>
  <div class="tab-pane" id="bar">Bar</div>
</div>

Javascript

$('.nav a:not(".external")').click(function (e) {
  e.preventDefault()
  $(this).tab('show')
})
Rabbi answered 6/3, 2014 at 17:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.