Background color of the selected option

I am writing a drop-down menu with several options and their colors. I have successfully painted the background of each option; however, after the selected background color is not displayed.

Is there any way to change this behavior? An example of my HTML is below:

<select> <option style="background-color: green">Successful</option> <option style="background-color: orange">Process Failure</option> <option style="background-color: purple">Abandoned</option> </select> 

and also here: http://jsfiddle.net/H8HVm/1/ .

Thanks!

+7
html css
source share
1 answer

So, you can use Jquery to read the class selected option , and then set the class as class for <select> . Here is the code followed by the fiddle ...

CSS

 .green { background-color: green; } .orange { background-color: orange; } .pink { background-color: pink; } 

Jquery

 $("#color_me").change(function(){ var color = $("option:selected", this).attr("class"); $("#color_me").attr("class", color); }); 

HTML

 <select id="color_me" class=""> <option class="green">successful</option> <option class="orange">process failure</option> <option class="pink">abandoned</option> </select> 

Here's the fiddle: http://jsfiddle.net/DrydenLong/3QUN6/

UPDATE

Upon request, here is a breakdown of my code above:

 $("#color_me").change(function(){ 

This line calls the function when the element with id in "color_me" is changed. that is, an option is selected from the selection list.

  var color = $("option:selected", this).attr("class"); 

This defines the color variable as independent of the class currently selected option . This variable refers to the DOM element that we refer to in the first line. Basically, this ensures that we get the class from the correct <select> ie <select> that we just clicked on.

  $("#color_me").attr("class", color); }); 

This line assigns the color variable defined above as the class element with id to #color_me .

+7
source share

All Articles