javascripthtmldropdown

Show different tabs when selecting in dropdown


I want to display different tab based on the selected item. This is working before when I am using buttons but when I changed it to dropdown menu it stopped working.

HTML:

<option class="tab">
        <select class="tablinks" onclick="openCity(event, 'AT3')" id="defaultOpen">Transatlantic 3</select>
        <select class="tablinks" onclick="openCity(event, 'AT4')">Transatlantic 4</select>
         <select class="tablinks" onclick="openCity(event, 'AL5')">Transatlantic 5</select>
      </option>

            <div id="AT3" class="tabcontent">
                <img src="images/AT3 (via CoGH)_20250118.jpg" class="service-map">
            </div>

            <div id="AT4" class="tabcontent">
                <img src="images/AT4 (via CoGH)_20250118.jpg" class="service-map">
            </div>

            <div id="AL5" class="tabcontent">
                <img src="images/AL5 (via CoGH)_20250118.jpg" class="service-map">
            </div>

JS:

    function openCity(evt, cityName) {
  var i, tabcontent, tablinks;
  tabcontent = document.getElementsByClassName("tabcontent");
  for (i = 0; i < tabcontent.length; i++) {
    tabcontent[i].style.display = "none";
  }
  tablinks = document.getElementsByClassName("tablinks");
  for (i = 0; i < tablinks.length; i++) {
    tablinks[i].className = tablinks[i].className.replace(" active", "");
  }
  document.getElementById(cityName).style.display = "block";
  evt.currentTarget.className += " active";
}
document.getElementById("defaultOpen").click();

Solution

  • options belong in selects, not the other way around.

    You can also simplify the openCity function quite a bit:

    function openCity(cityName) {
      for (const tab of document.querySelectorAll(".tabcontent")) {
        tab.style.display = tab.id === cityName ? "" : "none";
      }
    }
    openCity(document.querySelector("select.tab").value);
    <select class="tab" value="AT3" onChange="openCity(event.target.value)">
      <option value="AT3">Transatlantic 3</option>
      <option value="AT4">Transatlantic 4</option>
      <option value="AT5">Transatlantic 5</option>
    </select>
    
    <div id="AT3" class="tabcontent">
      AT3
      <img src="images/AT3 (via CoGH)_20250118.jpg" class="service-map">
    </div>
    
    <div id="AT4" class="tabcontent">
      AT4
      <img src="images/AT4 (via CoGH)_20250118.jpg" class="service-map">
    </div>
    
    <div id="AT5" class="tabcontent">
      AT5
      <img src="images/AL5 (via CoGH)_20250118.jpg" class="service-map">
    </div>