0

I have HTML like this one:

<select onclick="colorchanger()">
  <option name="white" value="0">--Select--</option>
  <option name="red" value="1">Work</option>
  <option name="green" value="2">Doesn't Work</option>
</select>

I need to change select box color, when option is selected. I understand how to change color by using value, but i need to use name. Can anyone help? How to write javascript for this function?

Mamun
  • 66,969
  • 9
  • 47
  • 59

2 Answers2

1

Try the following:

function colorchanger(op){
  var color = op.options[op.selectedIndex].getAttribute('name');
  op.style.backgroundColor=color;
}
<select onclick="colorchanger(this)">
  <option name="white" value="0">--Select--</option>
  <option name="red" value="1">Work</option>
  <option name="green" value="2">Doesn't Work</option>
</select>
Mamun
  • 66,969
  • 9
  • 47
  • 59
0

Use the 'onchange' handler. Shouldn't be necessary to change the color every click.

function colorChanger(select) {
  var color = select.options[select.selectedIndex].getAttribute('name');
  select.style.backgroundColor=color;
};
<select onchange="colorChanger(this);">
  <option name="white" value="0">--Select--</option>
  <option name="red" value="1">Work</option>
  <option name="green" value="2">Doesn't Work</option>
</select>
Robert Wade
  • 4,918
  • 1
  • 16
  • 35