How can I apply a CSS background color to only the selected option? If I apply a class to the select object, it styles all options. If I apply the desired classes to the options, I can see the styling fine for all the options when the select box is expanded. But when the select box is collapsed, the styling for the selected option is gone. I observe this behavior in the latest versions of Chrome and Firefox.
Here is some super basic example code. Without the jQuery, the selected option always appears unstyled. With the jQuery, once a “modified” option is selected, all options are styled as “modified”. I haven’t been able to figure out a way around this… Any ideas?
I do not want to change the styling of the options. Only to be able to see the styling of any given option when it is selected without overriding the styling of the others.
<style>
select.modified,
option.modified{
background-color: red;
}
</style>
<select id="example">
<option value="bird" class="modified">bird</option>
<option value="cat">cat</option>
<option value="dog" class="modified">dog</option>
</select>
<script>
$('#example').on('change',function(){
$(this).prop('class',$(this).find('option:selected').prop('class'));
});
</script>
I have found the best workaround for this issue. Basically I have to remove any classes from the selected option on focus, and add it back those classes on blur. This seems to do the trick fairly well.