Hamid K Hamid K - 2 years ago 79
HTML Question

send request to server for active bootstrap nav-pills

I am using Twitter Bootstrap v3 to create "nav-pills". Each of my tabs has a Bootstrap table that I update the values every 5 seconds. My Java script code for one table update is like below:

function LoadpData()
$(function() {
return false;

setInterval( LoadpData, 5000);

Sub section of my HTML file:

<ul class="nav nav-pills" id="Tabs">
<li class="active"><a href="#Press" data-toggle="tab">Pr</a></li>
<li><a href="#Fl" data-toggle="tab">Fl</a></li>
<li><a href="#Te" data-toggle="tab">Te</a></li>
<li><a href="#Pu" data-toggle="tab">Pu</a></li>
<li><a href="#Va" data-toggle="tab">Co</a></li>

What I would like to do is to find which tab is active and then update the data only for the table on that tab. So I was thinking of adding an if statement to the top of each LoadData() JS function to check and see if that tab is active or not, if yes then send the .getJSON request to the server to get the values, otherwise do nothing. I searched and found that I should be able to find the active tab by using this selector $('#Tabs li.active'). Also each of my tabs has a unique href attribute so using this selector $('#Tabs a[href="#Fl"]'), I should be able to get the jquery object and see if it is the active one or not. I am new to jquery, I appreciate if you could help me to find the solution.

function LoadpData()
// if ($('#Tabs li.active') = $('#Tabs a[href="#Fl"]')){
// $(function() {
// $.getJSON(..........);
// return false;
// });
// }

Answer Source

You can use a script like :

    $(document).ready(function() {
      setInterval(function() {
      }, 3000);

      function findAndUpdate() {
        // Find the active tab 
        var activeTab = $("#tabs").find("li.active");
        var activeTabIndex = activeTab.index();

        // Update the table according to index
        // var str = "";
        switch (activeTabIndex) {
          case 0:
            // update code for tab 0 table
          case 1:
            // update code for tab 1 table
          case 2:
            // update code for tab 2 table
          case 3:
            // update code for tab 3 table
            // default case             

      // if you want it should also be updated as soon as a user switches to a new tab, then    
      $("#tabs").on("click", "li", function() {
        setTimeout(function() {
        }, 30);
        // setting timeout is required as the tab should first change and then this function should be called
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download