Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing text color in SELECT boxes

Tags:

html

jquery

css

so I've spent the last hour searching, finding many answers here on Stack Overflow and on other sites. But none of them work.

I want to be able to dynamically set the color of the text in a SELECT drop-down box based on an item that's chosen, using jQuery.

I can change the background color easily:

$('#selectBox').css("background-color", "red");

But if I do this:

$('#selectBox').css("color", "red");

It doesn't work. The text stays black.

Other searching has revealed ::selection but that appears to apply to the style of user-selected text (such as for copy/paste).

Furthermore, I've tried using CSS classes like this:

option.red { color: red }

And using addClass() to change the class, but again, it no worky.

I've tested this in Firefox, Chrome, and Safari.

What am I doing wrong? Thanks!

like image 377
RobG Avatar asked Jul 30 '13 00:07

RobG


2 Answers

You need to change the color of the text in the <option> elements.

$("#selectBox").find("option").css("color", "red");
like image 57
Andy Jones Avatar answered Sep 29 '22 21:09

Andy Jones


I've created a fiddle for you. When you select an option from the dropdown, the text color changes dynamically depending on the option's ID.

EXAMPLE

Is this what you are looking for?

<select class="selectBox" id="selectBox">
    <option id="yellow">Yellow</option>
    <option id="red">Red</option>
    <option id="blue">Blue</option>
</select>



$("select").change(function () {
    var ID = $(this).children(":selected").attr("id");
    $('#selectBox').css('color', ID);
});
like image 38
Thanos Avatar answered Sep 29 '22 20:09

Thanos