slin
slin

Reputation: 3

Change select background to match selected option background

I have a simple query here:

I built a simple select with 2 different colored options: red and green.

.green { color: #217A23; }
.red    { color: #AA0000; }

<select id="select">
    <option class='green'>green</option>
    <option class='red'>red</option>
</select>

I'd like the select text WHEN CLOSED to match the selected text's color.

Thus, after selecting green in the dropdown, I would like the select text to be green as well. Right now, I can select the green text, but when the menu closes, the word "green" is still black in color.

Does this require jQuery to do?

http://jsfiddle.net/8zkx9yu0/

Upvotes: 0

Views: 132

Answers (2)

Anurag G
Anurag G

Reputation: 282

Use following code :

$("#select").on('change',(e)=>{
 // to make backgroud color
    $('body').css({background:e.target.value});
   $(e).removeClass().addClass($(e).find("option:selected").attr("class"););
})

Upvotes: 0

matthias_h
matthias_h

Reputation: 11416

You could do it like this, using your existing classes:

$("select").change(function() {
	let color = $(this).find("option:selected").attr("class");
  $(this).removeClass().addClass(color);
})
.green_bg { background-color: #217A23; }
.red_bg	{ background-color: #AA0000; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="select">
    <option>Select</option>
    <option class='green_bg'>green</option>
    <option class='red_bg'>red</option>
</select>

Upvotes: 1

Related Questions