I have a <select>
on my HTML page with several <option>
s; some options are disabled (The select is not disabled). I can style the disabled options:
select option:disabled
{
color: red;
}
However, I would also like to style the selected item if it is disabled. It is not possible for the user to get to this state, but it is possible for the page to be served in this state.
How can I style a select if its selected item is disabled?
If using js is not a problem,
You can do something like this on page load
event:
var elem = document.getElementById('idOfYourSelect');
var selectedOption= elem[elem.selectedIndex];
if(selectedOption.disabled == true){
elem.style.color='red'; // apply the styles
}
and change it back to normal on selecting it (if you want to)
elem.onclick= function(){
elem.style.color='initial'; // revert back to normal style
}
check this fiddle
This option makes use of the selected
attribute, and it also uses jQuery. Here is a fiddle to show an example: JsFiddle
<select>
<option>test1</option>
<option selected disabled>test2</option>
<option>test3</option>
<option>test4</option>
</select>
$('select > option:selected:disabled').each(function(){
$(this).parent().css("color","red");
});
$('select').change(function(){
$(this).css("color", "black");
});
/*reset color for options*/
select option:not(:disabled) {color:black;}
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