Home > Software engineering >  How to hide-show multiple divs using jQuery?
How to hide-show multiple divs using jQuery?

Time:10-04

Alright, so I want to show two divs when selecting on of the options in my selector.

This is what I have currently, works great and hiding and showing elements based on option selected. But doesnt work If i want 2 divs to show on based on sections. Help would be much appreciated.

$(function() {
  $('#colorselector').change(function() {
    $('.colors').hide();
    $('#'   $(this).val()).show();
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<Select id="colorselector">
  <option value="red">Red</option>
  <option value="yellow">Yellow</option>
  <option value="blue">Blue</option>
</Select>
<div id="red"  style="display:none"> red... </div>
<div id="yellow"  style="display:none"> yellow.. </div>
<div id="blue"  style="display:none"> blue.. </div>

CodePudding user response:

Not sure what 2 div's you want to show, but hes an example. I've switch out id for a command class by color:

$(function() {
  $('#colorselector').change(function() {
    $('.colors').hide();
    $('.colors.'   $(this).val()).show();
  });
});

Demo

$(function() {
  $('#colorselector').change(function() {
    $('.colors').hide();
    $('.colors.'   $(this).val()).show();
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<Select id="colorselector">
  <option value="red">Red</option>
  <option value="yellow">Yellow</option>
  <option value="blue">Blue</option>
</Select>
<div  style="display:none"> red... </div>
<div  style="display:none"> yellow.. </div>
<div  style="display:none"> blue..1 </div>

<div  style="display:none"> blue..2 </div>

CodePudding user response:

If you want to hide/show more than one element then you should work with class names instead of IDs:

$(function() {
  $('#colorselector').change(function() {
    $('.colors').hide()
    if (this.value>"") $('.colors.' this.value).show();
  });
});
.colors {font-weight:900; padding:10px; color: white}
.red {background-color:red}
.yellow {background-color:yellow; color:black;}
.blue {background-color:blue}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<Select id="colorselector">
  <option value="">select a color ...</option>
  <option value="red">Red</option>
  <option value="yellow">Yellow</option>
  <option value="blue">Blue</option>
</Select>
<div  style="display:none"> red... </div>
<div  style="display:none"> yellow.. </div>
<div  style="display:none"> blue.. </div>
<h2>Another section with further divs</h2>
<div  style="display:none">more red... </div>
<div  style="display:none">and yellow.. </div>
<div  style="display:none">or even blue.. </div>

  • Related