Reputation: 592
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!
Upvotes: 6
Views: 20839
Reputation: 153
I think the CSS changes with select tag would be conflict with other browser, specially with internet explorer.
If you have such a specific requirement then try this jQuery function to get perfect result.
http://adam.co/lab/jquery/customselect/
Upvotes: 0
Reputation: 3059
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.
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);
});
Upvotes: 3
Reputation: 6275
You need to change the color of the text in the <option>
elements.
$("#selectBox").find("option").css("color", "red");
Upvotes: 8
Reputation: 39777
You are doing nothing wrong, this behavior is a limitation of the SELECT element. There is very little you can do with it via CSS.
I suggest looking into custom dropdown controls (there're several pretty good jQuery ones)
Upvotes: 2