Home:ALL Converter>How to change background color only of selected option with javascript?

How to change background color only of selected option with javascript?

Ask Time:2019-08-02T17:55:49         Author:Sygol

Json Formatter

I'm trying to change background color when user selects some option. I did it with onchange function that simply contains:

function colorSameValues(select, color){
    for (var i=0; i<selects.length; i++){
        if (selects[i].value ==='') selects[i].style.backgroundColor='';
        if (selects[i].value === select.value) selects[i].style.backgroundColor=color;
    }
}

but it changes background color of all options.

I also saw on the internet how to change color of selected option, but it doesn't change option that is displayed, like here (first response) - Change the color of an option when selected - JavaScript

I would like to color displayed option, and when user clicks on this select to see other options I would like them not to be colored at all. Any ideas?

This is what I am trying to get

Author:Sygol,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/57324098/how-to-change-background-color-only-of-selected-option-with-javascript
Syed mohamed aladeen :

Try like this.\n\nI added a css for option background. and in JS, I set the background for select box.\n\n\r\n\r\nfunction changeColor(colorParam) {\r\n let color = colorParam.value.toLowerCase();\r\n var optionElement = document.getElementById('rgb');\r\n optionElement.style.background = color;\r\n};\r\noption{\r\n background:#fff;\r\n}\r\n<select onchange=\"changeColor(this);\" class=\"color\" id=\"rgb\">\r\n <option id=\"red\" value=\"Red\">Red</option>\r\n <option id=\"green\" value=\"Green\">Green</option>\r\n <option id=\"blue\" value=\"Blue\">Blue</option>\r\n <option id=\"white\" value=\"White\">White</option>\r\n <option id=\"pink\" value=\"Pink\">Pink</option>\r\n</select>",
2019-08-02T10:15:14
ellipsis :

You have to access the selected option and change the background\n\n\r\n\r\nfunction a(e)\r\n{\r\ne.options[e.selectedIndex].style.backgroundColor=e.options[e.selectedIndex].textContent;\r\nconsole.log(e.options[e.selectedIndex].textContent)\r\n}\r\n<select onchange=\"a(this)\">\r\n<option>Red</option>\r\n<option>Blue</option>\r\n<option>Green</option>\r\n</select>",
2019-08-02T10:03:24
yy