views:

128

answers:

4

Here is my run-of-the-mill drop down:

<select name="">
  <option value="">--Select One--</option>
  <option value="textarea">Text Area</option>
  <option value="textbox">Text Box</option>
  <option value="checkbox">Check Box</option>
  <option value="dropdown">Drop Down</option>
</select>

What I want to do is show show/hide other elements on the page based on if certain options are selected from the drop down.

So if "Text Area" was selected, then a div with the ID "textarea_fields" would show. If something else was then selected, that would hide and the other element would show for that select option.

I'm using jQuery, so using what that library offers is certainly an option.

+7  A: 

Assuming each div has the class ".panel"

$("select").change(function(){
  $(".panel").hide().filter("#"+ $(this).val() +"_fields").show();
});

You could expand upon this basis to see if the new selection matches that is currently visible if you like. You can determine which is presently opened like this:

var currPanel = $(".panel:visible").attr("id");
Jonathan Sampson
Exactly what I needed. Thanks!
Shpigford
+1 Great answer
Doug Neiner
+1  A: 

You'll probably want to put the divs in a class like this:

<div class='theFields' id='textarea_fields'>...</div>    
<div class='theFields' id='checkbox_fields'>...</div>

Then you can do something like this:

$("select").change(function() {
  $(".theFields").hide(); // hide all field divs
  $("#"+$(this).val()+"_fields").show(); // the the one you want
});
gnarf
A: 

Oh well, since I've already spent some time coding this up, might as well post the entire codes.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;
<html xmlns="http://www.w3.org/1999/xhtml"&gt;
<head>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"&gt;&lt;/script&gt;

    <script type="text/javascript">
    $(function() {
      $("#elements > *").hide();
      $("#selector").change(function(){
          $("#elements > *").hide();
          if($("#selector").val()) //if selected has value, then show the selected one
            $("#" + $("#selector").val()).show();
      });
    });

    </script>
</head>
<body>
<select id="selector">
  <option value="">--Select One--</option> <!-- this hides all -->
  <option value="textarea">Text Area</option>
  <option value="textbox">Text Box</option>
  <option value="checkbox">Check Box</option>
  <option value="dropdown">Drop Down</option>
</select>

<div id="elements"> <!-- container for the input elements-->
    <textarea id="textarea"></textarea>
    <input type="text" id="textbox" />
    <input type="checkbox" id="checkbox" />
    <select id="dropdown"><option>...</option></select>
</div>
</body>
</html>
o.k.w
A: 

o.k.w - thanks so much for posting that! :-) just made my day

Markgt