9

I have a selector sitting in a table cell. The table row has a color, so using CSS I can change the drop-down's background to the same color by using background-color:inherit; However, it changes the color of the entire box with all options.

Is it possible to change the color of the selected option only, if not with CSS perhaps with a help of jQuery?

santa
  • 12,234
  • 49
  • 155
  • 255

3 Answers3

10

Everything is possible with jQuery :) You should try this:

$('.mySelect').change(function () {
    $(this).find('option').css('background-color', 'transparent');
    $(this).find('option:selected').css('background-color', 'red');
}).trigger('change');

And here is a live demo

Hope that helps!

  • Ronn's answer takes into account the selected item when inactive and when clicked on and expanded. – Ohiovr Dec 01 '17 at 13:02
4

I was able to do it by first setting the background color of the SELECT element to what I wanted resulting in all options being that color. Then I made all the options a specific color scheme. Finally I made the selected option the same color scheme as the SELECT element so the option shows the same color in the drop down list.

$.each($('select'), function(i,v) {

    theElement = $(v);
    theID = theElement.attr('id');

    // Set the SELECT input element to green background with white text

    theElement.css('background-color', 'green');
    theElement.css('color', 'white');

    // Set all the options to another color (note transparant will show the green)

    $('#'+theID).find('option').css('background-color', 'white');
    $('#'+theID).find('option').css('color', 'black');

    // Finally set the selected option to the same values as the SELECT element

    $('#'+theID).find('option:selected').css('background-color', 'green');
    $('#'+theID).find('option:selected').css('color', 'white');
});
Perception
  • 79,279
  • 19
  • 185
  • 195
Ronn
  • 41
  • 1
3

You should be able to do this with jQuery. I may be wrong (see David Thomas' comment), but try:

$("option[value='myValue']").css('background-color', 'red');
thirtydot
  • 224,678
  • 48
  • 389
  • 349
jtfairbank
  • 2,311
  • 2
  • 21
  • 33