Reputation: 25348
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.
Upvotes: 2
Views: 2013
Reputation: 25810
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">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<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>
Upvotes: 0
Reputation: 268344
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");
Upvotes: 8
Reputation: 106332
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
});
Upvotes: 1