Tony Tambe Tony Tambe - 2 months ago 10
jQuery Question

Show Div and Hide All Others When Selected

This seems like it should be easy, but I haven't gotten it working yet. I have an html select element with 10 or so options. When the user selects one of the options, a Div is displayed by removing the .hidden class, which is just a class with display:none in the CSS. This all works fine, but when I select the next option, the previous div stays visible. I tried using .toggleClass, but that didn't work.

$(function () {
$("#calc-select").change(function () {
$('#' + $("#calc-select").val()).removeClass('hidden');
});
});

Answer

What you can do is save the previously selected option in a variable like so

$(function () {
  var prevSelected = $("#Test1");

  $("#calc-select").change(function () {
      $('#' + $("#calc-select").val()).removeClass('hidden');
      prevSelected.addClass('hidden');
      prevSelected = $('#' + $("#calc-select").val());
  });
}); 
.hidden {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="calc-select">
  <option>Test1</option>
  <option>Test2</option>
  <option>Test3</option>
  <option>Test4</option>
  <option>Test5</option>
</select>

<div id="Test1">
Content 1
</div>
<div id="Test2" class="hidden">
Content 2
</div>
<div id="Test3" class="hidden">
Content 3
</div>
<div id="Test4" class="hidden">
Content 4
</div>
<div id="Test5" class="hidden">
Content 5
</div>

Now what this jQuery code does is set the first selected value to the first option. Next what it does is remove hidden class, then adds the class back to the previous selected. Finally, it reassigns previously selected element to currently selected element. This way, the previously selected is constantly updated, and the divs are shown and hidden accordingly.

Comments