Can't figure out, how to change select box color, when option selected

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?

Upvotes: 0

Views: 73

Answers (2)

Robert Wade
Robert Wade

Reputation: 5003

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>

Upvotes: 0

Mamun
Mamun

Reputation: 68943

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>

Upvotes: 1

Related Questions