Can I switch between Twitter Bootstrap tab panes using a drop-down menu?

Looking for the best way to switch tabs using a dropdown select. I was thinking of using onChange event to manipulate the .active class, but there might be a better approach out there.

Please see below for a code snippet:

<select id="mySelect">
<option value="tab1">Tab 1</option>
<option value="tab2">Tab 2</option>
<option value="tab3">Tab 3</option>
</select>

<div id="myTabContent" class="tab-content">
  <div class="tab-pane fade in active" id="tab1">
    <div id="calendari_3">asd</div>
  </div>
  <div class="tab-pane fade" id="tab2">
    <div id="calendari_1">qwe</div>
  </div>
  <div class="tab-pane fade" id="tab3">
    <div id="calendari_2">asw</div>
  </div>
</div>

Answer №1

You have the option to manually trigger the 'show' method on any event.

http://jsfiddle.net/7Wv5h/40/ [updated]

JS:

// Ensure jQuery and Bootstrap are loaded as you listen for $(document).on('ready') 
$('#your-select').on('change', function (e) {
    // Use $(this).val() to specify the target value in your <option> elements.
    $('#the-tab li a').eq($(this).val()).tab('show');
    // If order isn't important, you can also use $(this).index().
    // $('#the-tab li a').eq($(this).index()).tab('show');
});

HTML:

<form>
    <select id='mySelect'>
        <option value='0'gt;Home</option>
        <option value='1'gt;Profile</option>
        <option value='2'gt;Messages</option>
        <option value='3'gt;Settings</option>
    </select>
</form>
<ul class="nav nav-tabs" id="myTab">
    <li class="active"><a href="#home">Home</a></li>
    <li><a href="#profile">Profile</a></li>
    <li><a href="#messages">Messages</a></li>
    <li><a href="#settings">Settings</a></li>
</ul>
<div class="tab-content">
    <div class="tab-pane active" id="home">Home content</div>
    <div class="tab-pane" id="profile">Profile content</div>
    <div class="tab-pane" id="messages">Messages content</div>
    <div class="tab-pane" id="settings">Settings content</div>
</div>

Answer №2

If you want to activate multiple sets of tabs with individual select boxes, you can utilize the JavaScript code provided below:

$('.select-nav').on('change', function(e) {
    var id = $(this).val();
    $('a[href="' + id + '"]').tab('show');
});

Credit for this solution goes to Flo-Schield-Bobby - thank you for the inspiration!

Answer №3

Here's a clever solution that eliminates the need for keeping track of links, just using the Select feature.

$('#mySelect').on('change', function (e) {
  var $optionSelected = $("option:selected", this);
  $optionSelected.tab('show')
});



<select class="form-control" id="mySelect">
    <option data-target="#home">Home</option>
    <option data-target="#profile">Profile</option>
    <option data-target="#messages">Messages</option>
    <option data-target="#messages">Settings</option>
</select>        


<div class="tab-content">
  <div class="tab-pane active" id="home">
    Home
  </div>
  <div class="tab-pane" id="profile">.
    Profile
  </div>
  <div class="tab-pane" id="messages">
    Messages
  </div>
  <div class="tab-pane" id="settings">
    Settings
  </div>
</div>

Answer №4

I was in search of a solution to manage multiple tabs on my webpage, but nothing else seemed suitable. Therefore, I took the initiative to create my own custom solution which you can find here: https://gist.github.com/kingsloi/7ab83b6781636df1fbf1

$(document).ready(function(){

//initialize index counter
var i = 0;

//modify all .nav-tabs, excluding those with the class .keep-tabs
$('.nav-tabs:not(.keep-tabs)').each(function(){

    //declare variables
    var $select,
        c       = 0,
        $select = $('<select class="mobile-nav-tabs-' +i+ ' mobile-tab-headings "></select>');

    //assign unique class to nav-tabs for independent functionality
    $(this).addClass('nav-tabs-index-'+i);

    //iterate through each <li>, converting them into an <option> by extracting text from the anchor tag
    $(this).children('li').each(function() {
        $select.append('<option value="'+c+'">' + $(this).text() + '</option>');
        c++;
    });

    //insert new <select> above <ul nav-tabs>
    $(this).before($select);

    //increment index counter
    i++
});

//on changing <select> element
$('[class^=mobile-nav-tabs]').on('change', function (e) {

    //extract index from selected option
    classArray      = $(this).attr('class').split(" ");
    tabIndexArray   = classArray[0].split("mobile-nav-tabs-");
    tabIndex        = tabIndexArray[1];

    //utilize boostrap tabs to display the selected option tab
    $('.nav-tabs-index-'+tabIndex+' li a').eq($(this).val()).tab('show');
});

});

You can also check out the JS fiddle link provided: http://jsfiddle.net/kingsloi/96ur6epu/

Answer №5

Thank you to everyone for your responses. I found Nathan Hiemstra's solution to be the most straightforward and user-friendly out of all.

However, I did notice that it only worked once in a "one and done" fashion. What I mean is that after cycling through all the panels, they would stop switching (at least in bootstrap 4.6.*).

Upon further investigation, I discovered that the .tab('show') method adds an "active" class to the selected option element. This makes sense since it is likely designed to work with nav tabs where only one is active at a time.

To fix this issue, I came up with a simple solution (although I'm not sure if it has any side-effects) - after calling .tab('show') on the option element, I added a call to .removeClass('active'). It occurred to me that the selected option is already the "active" one, so there is no need for this class. This small change transformed the functionality from "one and done" to lasting indefinitely.

I hope this minor adjustment proves helpful to others who may encounter the same issue.

Warm regards...

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

If I needed to include extra information within an element for easy retrieval using JavaScript

Using PHP, I have generated a list of products in a <select> element. Each product has a weight that I want to store within each <option> so I can access it later using Javascript. Is there a way to include the weight data directly in the HTML ...

Turn off body collisions in Cannon.js

I have a collection of planes that come together to create a terrain. Each plane has its own physics body using cannon.js (I utilize three.js for rendering). To conserve memory, I hide objects when the player moves too far away from them in the game world. ...

Organizing an array of objects within MUI cards based on social media platforms

I'm currently developing an application that showcases athlete data in a grid layout using MUI Grid. The colored borders on the left side of each card are determined by the corresponding social network associated with that athlete. https://i.sstatic. ...

Only the first iteration of a for loop is updating the array

This particular script is designed to work with an array of objects that are structured in the following way: {html:whatever number:number value}. function Org(data){ //array of objects var Data=data; for(var i=0; i<Data.length; i++){ var nums=[]; ...

The rule result is invalid due to the occurrence of the Function()

As I proceed with the upgrade from angular 6 to angular 7, I am diligently following the guidelines provided on the official Angular website. Upon executing the command to update angular/cli and core for version 7: $ ng update @angular/cli@v7 @angular/c ...

Output the selected row value using jQuery datatable selection

Below is the code snippet for searching in a table using jQuery datatable. I am aiming to reduce the number of records imported by implementing a search functionality before resorting to the built-in filtering feature. However, I have encountered an issue ...

Unable to invoke the jQuery function within CakePHP3

I am having trouble calling the jQuery function mentioned below in my CakePHP3 MVC project. There are no error messages, but nothing seems to be happening. The code is set up so that jQuery gets included automatically. The function I am trying to call sh ...

My HTML table is not printing at full width

Seeking assistance with creating a printable calendar using an HTML table. The calendar prints perfectly on a Mac, but when attempted on Windows in all browsers, it adds a 3" margin at the top regardless of CSS print settings. The client requires the cal ...

Issue with displaying svg images on Samsung Galaxy S7 mobile device

Having trouble filling an SVG image on my Samsung S7 mobile. It works perfectly fine on other devices. style="fill:white;" ...

Tips for invoking a function to automatically load elements on a jQuery mobile website

I am looking to keep my navbar HTML markup in a centralized location for easy editing. Currently, the body content of my index.html file appears like this: <div data-role="page" id="SomePage"> <div data-role="header"> <h1>Thi ...

Tips for utilizing flexbox to position a button to the right of an InputSelect

Struggling to position a button next to a dropdown? No matter what I attempt, the button keeps ending up above the dropdown. Ideally, I'd like it to appear alongside 'Select Organisation' as shown in the image below: https://i.sstatic.net/w ...

When an onblur event triggers a JavaScript function, it produces an alert message without modifying the innerHTML content within an element

One of the functions I wrote involves setting the innerHTML of a particular span with the id "mail_not_valid" to display a message when a user attempts to submit an invalid email address. This function works as intended. Additionally, another function is s ...

Utilizing a function upon page initialization in VueX

I am currently learning Vue with Vuex and I have created a method called 'llamarJson' which is used to retrieve JSON data. However, I am facing difficulties in using this method when the page loads. I have tried various approaches but have not be ...

Display numbers in Vue with the thousand separator

I am currently using a division calculator that is functioning properly, but I am not satisfied with the calculation results. The issue becomes more clear when you refer to the screenshots below. What I aim to achieve is to remove unnecessary zeros, add co ...

Entire body encompassing table

I am trying to create an HTML page with a table that spans the entire body and displays scrollbars when needed for both horizontal and vertical scrolling. Here is my current styling for the table: table { box-shadow: inset 0 0 10px #000; position: ...

Navigating through Index in #each in emberjs

Take a look at the code provided below: http://jsbin.com/atuBaXE/2/ I am attempting to access the index using {{@index}}, but it doesn't seem to be compiling. I believe that handlebars should support this feature: {{#each item in model}} {{@index} ...

Updating the content within the main body of the page rather than the sidebar in react-router v5

I have a question regarding the functioning of my sidebar and content. So, when I click on any item in the sidebar, the content changes accordingly. But what if I want to change the route directly from the content itself? That's where I'm facing ...

Align text in block beneath image on a new row using Bootstrap 4

I have set up a layout that I like, but I am looking to align the text under each image in a block directly below it. <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/css/bootstrap.min.css" rel="stylesheet"/> <div class="co ...

When comparing object strings, it is important to consider the differences between stringifying identity operators

While working on a reactjs component, my colleague encountered an issue with identity operators and JSON.stringify(). I was puzzled as to why he used stringify in the code, but what really confused me was why the if/else blocks were not functioning properl ...

Decide on the javascript/jquery libraries you want to include

My app is experiencing slow loading times on the home screen and students using it from school district computers are running into ERR_CONNECTION_RESET errors due to strict firewalls. The excessive loading of javascript and jquery libraries in the head of ...