Search code examples
javascripthtmljquerybootstrap-4bootstrap-select

How to make Bootstrap Select Dropdown act like a Tab List with option elements that have role=tab?


Is it possible to make Bootstrap Select Dropdown menu act like a Tab List? Basically, I want to change the content in the Select depending on what user has selected, from the <option> value. I saw there is bootstrap-select plugin, which basically is giving me 70% of the solution to my problem, except it is not a tab list it just has a dropdown menu "inside" the select element. Is it possible to change then functionality of this bootstrap-select to act like a tab panel or tab list?

Here is the picture to show you precisely what I want to do:

enter image description here

Code

    <select class="selectpicker">
      <option>Mustard</option>
      <option>Ketchup</option>
      <option>Barbecue</option>
    </select>
  <!--Show the different p tag depending on the option value-->
    <p>This is a Mustard tab</p>
    <p>This is a Ketchup tab</p>
    <p>This is a Barbecue tab</p>

Solution

  • Here, I learned how to do it, just with a little bit of researching on Stack Overflow.

    Basically I used the show which you can use on any tab with Bootstrap. Having said that, I learned (from someone on Stackoverflow, cant remember sorry) that when the option is selected in <select> tag, (option:selected), you can then see what is selected and then use that data-target, which will give you the id, to show that tab, like you would do if you are using simple tab without using the <select>

    $("#mySelect").on("change", function(e) {
      var $optionSelected = $("option:selected", this);
      $optionSelected.tab("show");
    });
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-zCbKRCUGaJDkqS1kPbPd7TveP5iyJE0EjAuZQTgFLD2ylzuqKfdKlfG/eSrtxUkn" crossorigin="anonymous">
    
    <select class="form-control selectpicker" id="mySelect">
      <option data-target="#mustard">Mustard</option>
      <option data-target="#ketchup">Ketchup</option>
      <option data-target="#barbecue">Barbecue</option>
    </select>
    
    <div class="tab-content">
      <div class="tab-pane active" id="mustard">Mustard</div>
      <div class="tab-pane" id="ketchup">. Ketchup</div>
      <div class="tab-pane" id="barbecue">Barbecue</div>
    </div>
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-fQybjgWLrvvRgtW6bFlB7jaZrFsaBXjsOMm/tB9LTS58ONXgqbR9W8oWht/amnpF" crossorigin="anonymous"></script>