Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Style text of select when the selected option is disabled

Tags:

html

css

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?

like image 647
ctrl-alt-delor Avatar asked Apr 02 '14 17:04

ctrl-alt-delor


2 Answers

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

like image 54
T J Avatar answered Oct 04 '22 10:10

T J


This option makes use of the selected attribute, and it also uses jQuery. Here is a fiddle to show an example: JsFiddle

HTML

<select>
    <option>test1</option>
    <option selected disabled>test2</option>
    <option>test3</option>
    <option>test4</option>
</select>

jQuery (onLoad)

$('select > option:selected:disabled').each(function(){
    $(this).parent().css("color","red");
});

$('select').change(function(){
    $(this).css("color", "black");
});

CSS

/*reset color for options*/
select option:not(:disabled) {color:black;}
like image 44
Gray Avatar answered Oct 04 '22 09:10

Gray