How can I show and hide elements based on selected option with jQuery?
173,398
Solution 1
You're running the code before the DOM is loaded.
Try this:
Live example:
$(function() { // Makes sure the code contained doesn't run until
// all the DOM elements have loaded
$('#colorselector').change(function(){
$('.colors').hide();
$('#' + $(this).val()).show();
});
});
Solution 2
<script>
$(document).ready(function(){
$('#colorselector').on('change', function() {
if ( this.value == 'red')
{
$("#divid").show();
}
else
{
$("#divid").hide();
}
});
});
</script>
Do like this for every value
Solution 3
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
}
});
Solution 4
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();
Author by
yogsma
Programmer. Founder of https://rentersvoices.com Developer of Android Application YFormulator (formerly Formulator). I used to write posts for Java Code Geeks here. Now I write better java code. Also you can check my github repositories github. You can download my ebook Spring Boot and Microservices Certified Scrum Master
Updated on January 13, 2021Comments
-
yogsma over 3 years
Here is my code. Why it doesn't work?
<Script> $('#colorselector').change(function() { $('.colors').hide(); $('#' + $(this).val()).show(); }); </Script> <Select id="colorselector"> <option value="red">Red</option> <option value="yellow">Yellow</option> <option value="blue">Blue</option> </Select> <div id="red" class="colors" style="display:none"> .... </div> <div id="yellow" class="colors" style="display:none"> ... </div> <div id="blue" class="colors" style="display:none"> ... </div>