How can I show and hide elements based on selected option with jQuery?
You are missing a :selected
on the selector for show()
- see the jQuery documentation for an example of how to use this.
In your case it will probably look something like this:
$('#'+$('#colorselector option:selected').val()).show();
To show the div while selecting one value and hide while selecting another value from dropdown box: -
$('#yourselectorid').bind('change', function(event) {
var i= $('#yourselectorid').val();
if(i=="sometext") // equal to a selection option
{
$('#divid').show();
}
elseif(i=="othertext")
{
$('#divid').hide(); // hide the first one
$('#divid2').show(); // show the other one
}
});
<script>
$(document).ready(function(){
$('#colorselector').on('change', function() {
if ( this.value == 'red')
{
$("#divid").show();
}
else
{
$("#divid").hide();
}
});
});
</script>
Do like this for every value
You're running the code before the DOM is loaded.
Try this:
Live example:
http://jsfiddle.net/FvMYz/
$(function() { // Makes sure the code contained doesn't run until
// all the DOM elements have loaded
$('#colorselector').change(function(){
$('.colors').hide();
$('#' + $(this).val()).show();
});
});