views:

310

answers:

3

Here is my code ..tell me what is wrong, 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>
+1  A: 

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();
Colonel Sponsz
No need to get the specific `option:selected`. Calling `.val()` on the select itself will return the value of the selected option. :o)
patrick dw
So it does. Every day's a school day, thanks.
Colonel Sponsz
+2  A: 

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();
    });

});
patrick dw
Works and +1 for linking to jsfiddle.net
KP
awesome! It worked!!
yogsma
@yogsma - Glad it helped. :)
patrick dw
@patrick - thanks for the link ..that's awesome tool.
yogsma
I have a small question. What should I do if I have to show same div section based on two or more select option values? I don't want to add additional div section. Like - Show red based on red and yellow values.
yogsma
@yogsma - You could simply give those `<option>` elements the same value, since you're using the `value` attribute to grab the proper `div`.
patrick dw
oh..right!! thanks @patrick
yogsma
A: 

edit: nvm, I commented a small piece of code for testing & forgot to put uncomment it afterwards..

Mike