Change Text Color of Selected Option in a Select Box

liquiddreams

New Member
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.\[code\]<select id="mySelect" class="yellowText"> <option class="greenText" value="http://stackoverflow.com/questions/15755770/apple" >Apple</option> <option class="redText" value="http://stackoverflow.com/questions/15755770/banana" >Banana</option> <option class="blueText" value="http://stackoverflow.com/questions/15755770/grape" >Grape</option></select>\[/code\]So if I select Banana, the text should change from yellow to red.I have tried:\[code\]onchange="this.style.color = this.options[this.selectedIndex].style.color;"\[/code\]But this only works if I define my styles within the option tags inside html document.I have also tried Javascript:\[code\]function setSelectColor(thisElement){var thisElem = document.getElementById(thisElement);var thisOption = thisElem.options[thisElem.selectedIndex];var newColor = getStyle(thisOption,"color");alert("New Color: "+ newColor);}\[/code\]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:\[code\]function getStyle(oElm, strCssRule){ var strValuehttp://stackoverflow.com/questions/15755770/= ""; if(document.defaultView && document.defaultView.getComputedStyle){ strValue = http://stackoverflow.com/questions/15755770/document.defaultView.getComputedStyle(oElm,"").getPropertyValue(strCssRule); } else if(oElm.currentStyle){ strCssRule = strCssRule.replace(/\-(\w)/g, function (strMatch, p1){ return p1.toUpperCase(); }); strValue = http://stackoverflow.com/questions/15755770/oElm.currentStyle[strCssRule]; } return strValue;}\[/code\]How can I solve this with Javascript?
 
Back
Top