0

I attempted to change the color of an option like this but doesn't seem to change the color specified in the style. What am I missing here?

<select name="test" >
  <option value="green" style="color:green;">this is green</option>
  <option value="red" style="color:red;">this is red</option>
</select>

EDIT: Screenshot of the result running on my computer Mac OS (Chrome Version 67.0.3396.79 (Official Build) (64-bit))
enter image description here

Bsonjin
  • 438
  • 1
  • 4
  • 14

3 Answers3

0

Update 01

Give this a try, it is effectively the same, but see if chrome on mac is happy with this :-)

function selectionChanged(){
    var selectElement = document.getElementById('test');
    var selectedOption = selectElement.selectedIndex;
    selectElement.style.color = selectElement.options[selectedOption].value;
}
<select name="test" id="test" onchange="selectionChanged()" style="color: green">
    <option value="green" style="color:green;">this is green</option>
    <option value="red" style="color:red;">this is red</option>
</select>

Original answer:

Perhaps what you need is....

<select name="test" id="test" onchange="document.getElementById('test').style.color = document.getElementById('test').options[document.getElementById('test').selectedIndex].value" style="color: green">
  <option value="green" style="color:green;">this is green</option>
  <option value="red" style="color:red;">this is red</option>
</select>
  1. Note that the green color is hard-coded for select element since the first / default option is green
  2. and then onchange of select will re-apply the style based on selected option. (You could also create a specific function in JS, but this code will do the trick if your requirements are not going to grow)
AD8
  • 2,168
  • 2
  • 16
  • 31
  • 1
    The OP using mac + Chrome. Have you tested on this environment? – Mosh Feu Jun 25 '18 at 07:07
  • 1
    This doesn't work on Mac OS (Chrome). But it works in Firefox – Bsonjin Jun 25 '18 at 07:09
  • Ah, my bad, I don't have access to mac, It worked for me on chrome Windows. Perhaps I will update an answer soon with alternate approach if that works. – AD8 Jun 25 '18 at 07:10
0

I think you want to change the color of the select based on the selection. Therefore;

<select name="test" id="test" onchange="changeColor()">
  <option value="green" style="color:green;">this is green</option>
  <option value="red" style="color:red;">this is red</option>
</select>
<script type="text/javascript">
   function changeColor() {
    document.getElementById("test").style.color = document.getElementById("test").value;
   }
</script>
Laazo
  • 467
  • 8
  • 22
-4

You could try to use colour code instead of "Red" / "Green"

Refer to below colour code, https://www.w3schools.com/cssref/css_colors.asp

Try below coding,

<font color="#FF0000">This is some text!</font>