Search code examples
jqueryhtml-select

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/


Solution

  • 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>