0

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');
Casey Cao
  • 341
  • 3
  • 15

3 Answers3

1

$("#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

Aloso
  • 5,123
  • 4
  • 24
  • 41
JDZ
  • 68
  • 5
1

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

ShuBham GuPta
  • 194
  • 2
  • 9
1

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.

Aloso
  • 5,123
  • 4
  • 24
  • 41