santa
santa

Reputation: 12512

Change color of selected option only

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?

Upvotes: 9

Views: 36423

Answers (3)

Ronn
Ronn

Reputation: 41

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');
});

Upvotes: 4

jtfairbank
jtfairbank

Reputation: 2307

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');

Upvotes: 3

Kristoffer Lundberg
Kristoffer Lundberg

Reputation: 876

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!

Upvotes: 10

Related Questions