Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
190
rated 0 times [  194] [ 4]  / answers: 1 / hits: 54827  / 11 Years ago, tue, august 6, 2013, 12:00:00

I'm writing a dropdown menu with several options and their colors. I have successfully colored the background of each option; however, once selected that background color doesn't show.


Is there a way to change this behavior? Example of my HTML 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>

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


More From » html

 Answers
36

You can use jQuery to read the class of the selected option then set that class as the class of the <select>. Here is the code, followed by a fiddle:




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

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

<script src=https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js></script>
<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 JSFiddle: http://jsfiddle.net/DrydenLong/3QUN6/


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


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

This line calls function when the element with the id of "color_me" is changed. i.e. an option from the select list is chosen.


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

This defines the variable color as whatever the class of the current selected option is. The this variable is referring to the DOM element we referenced in the first line. Basically this ensures that we are getting the class from the correct <select> i.e. the <select> we just clicked on.


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

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


[#76493] Monday, August 5, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kevonmoisesf

Total Points: 693
Total Questions: 101
Total Answers: 128

Location: Reunion
Member since Mon, Dec 28, 2020
3 Years ago
kevonmoisesf questions
Sat, Jan 23, 21, 00:00, 3 Years ago
Tue, Feb 18, 20, 00:00, 4 Years ago
Wed, Jun 12, 19, 00:00, 5 Years ago
;