sora0419
sora0419

Reputation: 2378

Change Style of Specific Option in SelectMenu Using jQuery

I'm trying to modify some existing code. I want to use jQuery to change the style of some items in a dropdownlist.

I have my dropdownlist structured like this:

<select name="dept" id="dept">
  <option value="01">DeptA</option>
  <option value="02">DeptB</option>
  <option value="03" class="station">DeptC</option>
  <option value="04" class="station">DeptD</option>
  <option value="05" class="station">DeptE</option>
  <option value="06" class="station">DeptF</option>
  <option value="07" class="station">DeptG</option>
  <option value="08">DeptH</option>
</select>

I want to be able to change the font color or the background color of the option that has class="station" (aka. DeptC-G).

I tried the below method:

<script>
$(function() {    
  $( "#dept" ).selectmenu().selectmenu( "menuWidget" );
  /*$( "option" ).each(function() {
    if ( $( this ).hasClass("station") ) {
      //alert(this.text);
      $(this).addClass("testClass");
    }
  });*/
});
</script>

<style>
  .testClass
  {
    color:blue;
    background:pink;
  }
</style>

The commented section does not work, it will do the alert part, but the style was never applied.

I tried to use

$("#dept").selectmenu().selectmenu( "menuWidget" ).addClass("testClass");

but this will apply the style to every options instead of the specific ones.

I had done some research and I found this which from the question looks very similar to what I'm looking for. However, I tried the given solutions none of them work for me. No errors, just no style was applied.

Any help is appreciated :)

EDIT_01:

This is how it looks like in IE11, the list shift based on the original selection. (I know this is how IE11 render dropdownlist, but we are going to change it)

enter image description here

We will need the dropdownlist to look like what it's like in IE8, like below. And somehow the style was not applied.

enter image description here

Upvotes: 1

Views: 3309

Answers (1)

JGV
JGV

Reputation: 5197

Here is a possible solution:

var options = $('#dept').find('option');

$.each(options, function(i, opt){

if ($(opt).hasClass('station'))
  {
    $(opt).addClass('highlight');
  }
  
});
.highlight
  {
    color:red;
    background:yellow;
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="dept" id="dept">
  <option value="01">DeptA</option>
  <option value="02">DeptB</option>
  <option value="03" class="station">DeptC</option>
  <option value="04" class="station">DeptD</option>
  <option value="05" class="station">DeptE</option>
  <option value="06" class="station">DeptF</option>
  <option value="07" class="station">DeptG</option>
  <option value="08">DeptH</option>
</select>

Upvotes: 1

Related Questions