sjsc
sjsc

Reputation: 4652

Jquery: Select menu to show and hide certain div elements

I'm looking to create a select menu that shows and hide certain divs based on the selected option; something like this:

<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 the use selects "Choose Red", then the div for #red_options will show, and the #blue_options and #green_options will hide.

If the user goes back to the default option "Select color", the #red_options/#blue_options/#green divs are hidden.

How would I do that 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 that's not working correctly. Any ideas?

Upvotes: 4

Views: 3260

Answers (5)

boxfrommars
boxfrommars

Reputation: 71

$(".color_options").hide();
$('#color_selector').change(function(){
    var color = $("#color_selector").val();
    $(".color_options").hide();
    $("#" + color + "_options").show();
});

Upvotes: 1

James Curran
James Curran

Reputation: 103515

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

Upvotes: 1

user272808
user272808

Reputation:

I think in this case you should not show/hide different divs, but apply different classes for one div instead.

Upvotes: 0

cletus
cletus

Reputation: 625147

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

Upvotes: 4

Nick Craver
Nick Craver

Reputation: 630469

Try this:

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

This takes advantage of the matches in the drop down values and how you've named your divs, e.g. red = red_options

Upvotes: 7

Related Questions