I'm trying to change the text color of the option that is selected. It's working in IE but not in Firefox.
<html>
<head>
<script type="text/javascript">
$(document).ready(function(){
$("option:selected").css("color", "green");
});
</script>
</head>
<body>
<select id="mySelect">
<option selected="selected">option 1</option>
<option>option 2</option>
<option>option 3</option>
</select>
</body>
</html>
UPDATED
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<script type="text/javascript">
$(document).ready(function(){
$("select").css("color", "green").focus(function() {
$(this).css('color', 'black');
}).blur(function() {
$(this).css('color', 'green');
});
});
</script>
</head>
<body>
<select id="mySelect">
<option selected="selected">option 1</option>
<option>option 2</option>
<option>option 3</option>
</select>
</body>
</html>
UPDATED 2
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<style type="text/css">
select.green{
color: green;
}
option {
color: black;
}
</style>
<script type="text/javascript">
$(document).ready(function(){
var green = $('option:selected', 'select').data('green');
if (green) {
$('select').addClass('green');
}
$('select').change(function() {
var green = $('option:selected', this).data('green');
if (green) {
$('select').addClass('green');
}
else {
$('select').removeClass('green');
}
});
});
</script>
</head>
<body>
<select id="mySelect">
<option selected="selected" data-green="true">option 1</option>
<option>option 2</option>
<option>option 3</option>
</select>
</body>
</html>
This might not be the solution you are looking for but you can do that in css:
option[selected] {
color: green;
}
This only works with browsers that support attribute selectors (IE7+)
EDIT:
After reading your comment I understand what you want to achieve. You want to make the select
green AND the selected element (option
) green (and the rest to black). You can do this by using the following css code:
select {
color: green;
}
option[selected] {
color: green;
}
option {
color: black;
}
See my JSFiddle. However the colours won't change after you select a different option.
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