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>
To show a hidden div when a select option is selected, you can set the value “style. display” to block.
jQuery hide() Method The hide() method hides the selected elements. Tip: This is similar to the CSS property display:none. Note: Hidden elements will not be displayed at all (no longer affects the layout of the page). Tip: To show hidden elements, look at the show() method.
Answer: Use the jQuery show() and hide() methods You can simply use the jQuery show() and hide() methods to show and hide the div elements based on the selection of radio buttons. The div boxes in the following example are hidden by default using the CSS display property which value is set to none .
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(); }); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With