Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I show and hide elements based on selected option with jQuery?

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> 
like image 401
yogsma Avatar asked Jun 04 '10 15:06

yogsma


People also ask

How can I show a hidden div when a select option is selected?

To show a hidden div when a select option is selected, you can set the value “style. display” to block.

Which method is used to hide selected elements in jQuery?

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.

How do you show and hide div elements based on the selection of radio buttons?

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 .


1 Answers

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();     });  }); 
like image 121
user113716 Avatar answered Oct 10 '22 13:10

user113716