[javascript] Change Text Color of Selected Option in a Select Box

I have a select box. The options have been styled with different colors via a CSS file that has been referenced. I want to be able to select an option and change the text color of the closed select box to the color of the chosen option.

<select id="mySelect" class="yellowText">
    <option class="greenText" value="apple" >Apple</option>
    <option class="redText" value="banana" >Banana</option>
    <option class="blueText" value="grape" >Grape</option>
</select>

So if I select Banana, the text should change from yellow to red.

I have tried:

onchange="this.style.color = this.options[this.selectedIndex].style.color;"

But this only works if I define my styles within the option tags inside html document.

I have also tried JavaScript:

function setSelectColor(thisElement){
    var thisElem = document.getElementById(thisElement);
    var thisOption = thisElem.options[thisElem.selectedIndex];
    var newColor = getStyle(thisOption,"color");
    alert("New Color: "+ newColor);
}

But this always returns the color: white. The getStyle function works everywhere else I use it so I do not believe that's the problem.

I got getStyle from this very website:

function getStyle(oElm, strCssRule){
    var strValue = "";
    if(document.defaultView && document.defaultView.getComputedStyle){
        strValue = document.defaultView.getComputedStyle(oElm, "").getPropertyValue(strCssRule);
    }
    else if(oElm.currentStyle){
        strCssRule = strCssRule.replace(/\-(\w)/g, function (strMatch, p1){
            return p1.toUpperCase();
        });
        strValue = oElm.currentStyle[strCssRule];
    }
    return strValue;
}

How can I solve this with JavaScript?

This question is related to javascript html css drop-down-menu colors

The answer is


CSS
select{
  color:red;
 }

HTML
<select id="sel" onclick="document.getElementById('sel').style.color='green';">
 <option>Select Your Option</option>
 <option value="">INDIA</option>
 <option value="">USA</option>
</select>

The above code will change the colour of text on click of the select box.

and if you want every option different colour, give separate class or id to all options.


JQuery Code:

$('#mySelect').change(function () {
    $('#mySelect').css("background", $("select option:selected").css("background-color"));
});

This will replace the select's background-color with selected option's background-color.

Here is an example fiddle.


<html>
  <style>
.selectBox{
 color:White;
}
.optionBox{
  color:black;
}

</style>
<body>
<select class = "selectBox">
  <option class = "optionBox">One</option>
  <option class = "optionBox">Two</option>
  <option class = "optionBox">Three</option>
</select>

ONE COLOR CASE - CSS only

Just to register my experience, where I wanted to set only the color of the selected option to a specific one.

I first tried to set by css only the color of the selected option with no success.

Then, after trying some combinations, this has worked for me with SCSS:

select {
      color: white; // color of the selected option

      option {
        color: black; // color of all the other options
      }
 }

Take a look at a working example with only CSS:

_x000D_
_x000D_
select {_x000D_
  color: yellow; // color of the selected option_x000D_
 }_x000D_
_x000D_
select option {_x000D_
  color: black; // color of all the other options_x000D_
}
_x000D_
<select id="mySelect">_x000D_
    <option value="apple" >Apple</option>_x000D_
    <option value="banana" >Banana</option>_x000D_
    <option value="grape" >Grape</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

For different colors, depending on the selected option, you'll have to deal with js.


You could do it like this.

jsFiddle

JS

var select = document.getElementById('mySelect');
select.onchange = function () {
    select.className = this.options[this.selectedIndex].className;
}

CSS

.redText {
    background-color:#F00;
}
.greenText {
    background-color:#0F0;
}
.blueText {
    background-color:#00F;
}

You could use option { background-color: #FFF; } if you want the list to be white.

HTML

<select id="mySelect" class="greenText">
    <option class="greenText" value="apple" >Apple</option>
    <option class="redText"   value="banana" >Banana</option>
    <option class="blueText" value="grape" >Grape</option>
</select>

Since this is a select it doesn't really make sense to use .yellowText as none selected if that's what you were getting at as something must be selected.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to css

need to add a class to an element Using Lato fonts in my css (@font-face) Please help me convert this script to a simple image slider Why there is this "clear" class before footer? How to set width of mat-table column in angular? Center content vertically on Vuetify bootstrap 4 file input doesn't show the file name Bootstrap 4: responsive sidebar menu to top navbar Stylesheet not loaded because of MIME-type Force flex item to span full row width How to implement drop down list in flutter? How can I create a dropdown menu from a List in Tkinter? How can I close a dropdown on click outside? Making a drop down list using swift? HTML: Select multiple as dropdown How to get selected value of a dropdown menu in ReactJS Avoid dropdown menu close on click inside Bootstrap 3 dropdown select How to make a drop down list in yii2? Android custom dropdown/popup menu

Examples related to colors

is it possible to add colors to python output? How do I use hexadecimal color strings in Flutter? How do I change the font color in an html table? How do I print colored output with Python 3? Change bar plot colour in geom_bar with ggplot2 in r How can I color a UIImage in Swift? How to change text color and console color in code::blocks? Android lollipop change navigation bar color How to change status bar color to match app in Lollipop? [Android] How to change color of the back arrow in the new material theme?