How to apply background-color to a selected option?
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
.