2

I have an HTML5 <select> with several <option> children, where each <option> has its own back and foreground colors. This is done via CSS and is easy enough.

What I would like to do is to maintain the <option> color in the <select> after the <option> has been selected. For example, let's say I have this (I'm not using CSS in the simple example below but in my real environment I am):

<select>
    <option style="color:red">ABC</option>
    <option style="color:blue" selected>DEF</option>
    <option style="color:green">GHI</option>
</select>

I would like to use CSS to somehow "transfer" the back and foreground colors of the chosen <option> to the <select> so that the <select> color is always in synch with the color of the chosen <option>. If the user selects the third option in my example, it should appear green when selected. Choosing the first option and the text appears red. When the <select> is initially displayed, it should have the back and foreground colors of the initial <option> (blue foreground, in the example above).

I can do this through jQuery but I'd prefer to use CSS but I feel it probably can't be done.

Tom Baxter
  • 2,110
  • 2
  • 19
  • 38
  • Interesting question. I don't believe this can be done with CSS alone. Still checking, but JS or PHP will probably be your best bet. – Michael Benjamin Jul 28 '15 at 03:30
  • @tom-baxter create jsFiddle with your code – Hitesh Siddhapura Jul 28 '15 at 03:34
  • As you need to detect the **change event** of `select` element, you need javascript/jquery i guess. And further Solution [Here](http://stackoverflow.com/questions/15755770/change-text-color-of-selected-option-in-a-select-box) – Suman KC Jul 28 '15 at 04:21
  • This worked for me: http://stackoverflow.com/questions/15755770/change-text-color-of-selected-option-in-a-select-box – Ricarte Nov 25 '16 at 21:03

2 Answers2

1

I have a solution I am happy with at the jsfiddle provided. The one caveat is that each <option> must have a background color set explicitly (it cannot inherit from the <select> as the <select> will have its background color changed as the selected <option> changes).

UPDATE Unfortunately, this "solution" only works in Chrome and Opera. So much for browser compatibility.

https://jsfiddle.net/herm0xvb/1/

Tom Baxter
  • 2,110
  • 2
  • 19
  • 38
0

You have to manually get CLASS and COLOR from selected option element

$(document).ready(function(){  
  $('select').change(function() {
      var opt =  $(this)[0].options[$(this)[0].selectedIndex];
    $(this)[0].style.backgroundColor = opt.style.backgroundColor;
    $(this)[0].className = opt.className;
  });
});
Matteo Rubini
  • 831
  • 5
  • 9