-1

I want to change the front color of dropdown list name. Here 2 Dropdown name list 1. Doctor Name 1 (Discount 10%) and 2. Doctor Name 2 (Discount 15%). But i want to change font color of only (Discount 10% ) (Font Color Red) and (Discount 15%) (Font color Blue) . How to change this?. please help me to solve that problem

<html>
<head>
</head>
<body>
<select name="">
    <option value="" >Select Doctor Name</option>
    <option value="1">Doctor Name 1 (Discount 10%)</option>
    <option value="2">Doctor Name 2 (Discount 15 %)</option>
</select>
</body>
<html>
Susant
  • 87
  • 2
  • 9

1 Answers1

0

I would use JavaScript for this solution since the code is easier to maintain if you have many options and you can also adjust the color of the selected item which you cannot do with pure CSS. This is my solution:

var colorSelect = document.getElementById('colorSelect');

// initialises all colors to the value given by data-color or black
function initColorSelect() {
  var options = colorSelect.getElementsByTagName('option');
  var selIndex = colorSelect.selectedIndex;
  for (var i = 0; i < options.length; ++i) {
    var color = '#000';
    if (options[i].hasAttribute('data-color')) {
     color = options[i].dataset.color;
    }
    options[i].style.color = color;
    if (i == selIndex) colorSelect.style.color = color;
  }
}

// changes the color of the selected item
function colorSelectChanged() {
  var option = this.options[this.selectedIndex];
  var color = '#000';
  if (option.hasAttribute('data-color')) {
    color = option.dataset.color;
  }
  colorSelect.style.color = color;
}

window.addEventListener('load', initColorSelect, false);
colorSelect.addEventListener('change', colorSelectChanged, false);
<body>
  <select id="colorSelect">
    <option value="">Select Doctor Name</option>
    <option value="1" data-color="#f00">Doctor Name 1 (Discount 10%)</option>
    <option value="2" data-color="#00f">Doctor Name 2 (Discount 15 %)</option>
  </select>
</body>
Anonymous
  • 902
  • 10
  • 23