user5863509 user5863509 - 2 months ago 7
jQuery Question

Change color of the dropdown text and add <optgroup> tag based on text using jquery

I have a dropdown populating from database with following text.

Item1
Item2*
Item3*
Item4

I want to change the color of the item2 & item3 to red (based on * symbol), item1 and item4 to green. Also group them as group1 and group2.

Result



Group1
Item1
Item4
Group2
item2*
item3*

How can I achieve this using jQuery.

Thanks

Answer

First filter the * and wrap them in <optgroup>, then wrap the rest

var $sel = $('#mySelect'),
  $starGroup = $('<optgroup label="Group 2" class="red-group">');

$sel.children().filter(function() {
  return $(this).text().indexOf('*') > -1;
}).appendTo($starGroup);

$sel.children().wrapAll('<optgroup label="Group 1" class="green-group">');

$sel.append($starGroup);
.red-group option {
  color: red
}
.green-group option {
  color: green
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="mySelect" size=6>
  <option value="">item 1</option>
  <option value="">item 2*</option>
  <option value="">item 3*</option>
  <option value="">item 4</option>
</select>

EDIT: to remove * modify the filter part to

$sel.children().filter(function() {
  var txt = $(this).text(),
      hasStar = txt.indexOf('*') > -1;
      if(hasStar){
         $(this).text(txt.replace('*',''))
      }
  return hasStar;
}).appendTo($starGroup);
Comments