JQuery: select a menu to show and hide certain div elements

I am looking to create a selection menu that displays and hides certain divs based on the selected option; something like that:

<select name="choose_colors" id="color_selector">
  <option value="select_color">Select color</option>
  <option value="red">Choose Red</option>
  <option value="blue">Choose Blue</option>
  <option value="green">Choose Green</option>
</select>

<div id="red_options" class="color_options">
  ...
</div>

<div id="blue_options" class="color_options">
  ...
</div>

<div id="green_options" class="color_options">
  ...
</div>

So, if you select β€œChoose Red,” a div for #red_options will appear, and #blue_options and #green_options will be hidden.

If the user returns to the default option "Choose color", the # red_options / # blue_options / # green divs are hidden.

How can I do this in jQuery? I thought it would be something like this:

<script>
  $(".color_options").hide();

  $('select[name="choose_colors"]').change(function () {
    if ("Select color") {
      $("#red_options").hide();
      $("#blue_options").hide();
      $("#green_options").hide();
    }
    if ("Red") {
      $("#red_options").show();
    }
    if ("Blue") {
      $("#blue_options").show();
    }
    if ("Green") {
      $("#green_options").show();
    }
  });
</script>

Of course, this is not working properly. Any ideas?

+3
source share
5 answers

Try the following:

$("#color_selector").change(function() {
  $(".color_options").hide();
  $("#" + $(this).val() + "_options").show();
}

divs, . red= red_options

+6
$("#color_selector").change(function() {
  var color = $(this).val();
  $("div.color_options").hide().filter("#" + color + "_options").show();
});
+4
 $('#color_selector').change(function () 
 { 
    $(".color_options").hide(); 
    var color = $(this).val();
    $('#'+color+'_options').show();
  }); 
+1
source
$(".color_options").hide();
$('#color_selector').change(function(){
    var color = $("#color_selector").val();
    $(".color_options").hide();
    $("#" + color + "_options").show();
});
+1
source

I think that in this case you should not show / hide different divs, but instead use different classes for the same div.

0
source

Source: https://habr.com/ru/post/1732742/


All Articles