Richard
Richard

Reputation: 7433

Changing the text colour of a selected disabled option

I have the following code:

select option:disabled:checked {
  color: grey;
}
<select>
  <option selected disabled>Initial Option</option>
  <option>One</option>
  <option>Two</option>
</select>

It did successfully select the right element. However, the problem is: I want to change the colour of the disabled option's text when it is selected (which is when we first load the page). Currently, I can only see the grey colour I have applied when I select another option in the dropdown select list. I want the initial selected colour to be grey to indicate that the user still has to choose another option. How can I achieve that?

Upvotes: 3

Views: 2047

Answers (3)

Udara Kasun
Udara Kasun

Reputation: 2216

This is a my idea for your problem, try this

$(document).ready(function(){
   $('#MySelect').val('Zero').change();   
});


$('#MySelect').on('change',function(){
   $($(this)).css("color", $(this).find("option").css('color','black'));
   
   var color = $(this).find("option[value="+$(this).val()+"]").attr('optioncolor');
   $($(this)).css("color", color);
   $($(this)).css("color", $(this).find("option[value="+$(this).val()+"]").css('color',color));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
 
 <select id="MySelect">
   <option value="Zero" selected optioncolor="red" >Zero</option>
   <option value="One" optioncolor="green">One</option>
   <option value="Two" optioncolor="yellow">Two</option>
 </select>

CodePen Example

Upvotes: 1

yimei
yimei

Reputation: 433

I added jQuery to add class to the selected option. Try this:

function selectOption() {
  var x = $('#select-dropdown').val()
  $('#select-dropdown option[value='+ x+']').attr("selected", true).attr("disabled", true)
}
select option:disabled:checked {
  color: grey;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<select id="select-dropdown" onChange="selectOption()">
  <option selected disabled>Initial Option</option>
  <option value="One">One</option>
  <option value="Two">Two</option>
</select>

Upvotes: 0

Harish
Harish

Reputation: 123

Try this :

.checked {
    color:green
 }


 <select>
   <option style="color:grey">Initial Option</option>
   <option class="checked">One</option>
   <option class="checked">Two</option>
 </select>

Upvotes: 0

Related Questions