Casey Cao
Casey Cao

Reputation: 341

How to change text color based on specific option?

I want to change the first option's color to #ccc, others remain #000, but it doesn't work.Why? thanks. I don't wnat to use change function, which I think it's unnecessary.

something like this: enter image description here

HTML:

  <select id="continent"> 
      <option value="-1">continent</option> 
      <option value="1">US</option> 
      <option value="2">UK</option> 
  </select> 

JS:

$("#continent option[value='-1']").css('color','#ccc');

Upvotes: 0

Views: 110

Answers (3)

JDZ
JDZ

Reputation: 68

$("#continent").change(function(){
    $("#continent").val() == "-1" ? $("#continent").css("color", "red") : $("#continent").css("color", "blue");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="continent"> 
    <option value="-1">continent</option> 
    <option value="1">US</option> 
    <option value="2">UK</option> 
</select>

Remember to preset the color of the default option

Upvotes: 1

ShuBham GuPta
ShuBham GuPta

Reputation: 324

here is solution

$('.mySelect').change(function () {
     if($(this).find("option:selected").attr("value")==2){
    $(this).find('option:selected').css('color', 'red');
    }else{
     $(this).find('option:selected').css('color', 'blue');
    }

});

In above code i use .find() method which is used for select child of selected element try this code in fiddle

Upvotes: 1

Aloso
Aloso

Reputation: 5387

Why do you want to use jQuery? This can be done with pure CSS.

#continent option {
  background-color: white; /* on XFCE the default background-color is #CCC! */
}
<select id="continent"> 
    <option value="-1" style="color:#cccccc">continent</option> 
    <option value="1">US</option> 
    <option value="2">UK</option> 
</select>

However you probably shouldn't do this, because it looks like the option was disabled, but it isn't. This is counterintuitive and against usability.

Apart from that, it looks different on other operating systems. This is how the snippet from above looks like on ubuntu with XFCE:

enter image description here

And this is what another solution looks like that also changes the color of the <select> to light gray if the 1st option is selected:

enter image description here

That's why you should either use <option value="-1" disabled> or another color.

Upvotes: 1

Related Questions