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!
You need to change the color of the text in the <option>
elements.
$("#selectBox").find("option").css("color", "red");
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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With