javascript – How do I change the background-color of a select element when an option is clicked?

Question:

I want to change the color of an item. There is a list item, but I use the background-color as the values ​​for this item.

<select style="background-color: red;" class="select new">
  <option style="background-color: green;" value="green"></option>
  <option style="background-color: yellow;" value="yellow"></option>
  <option style="background-color: blue;" value="blue"></option>
  <option style="background-color: red;" value="red"></option>
</select>

Tried through jQuery :

$(option).click(funсtion(){ $(select).style("background-color:red;") });

But it doesn't work that way. How do I change the color of the select element when I click on an option element?

Answer:

When you click on the option , you need to use the change event when the value of the select changes:

Pure JavaScript variant:

var select = document.querySelector('.select.new');
select.addEventListener('change', function() {
  select.style.backgroundColor = select.value
});
<select style="background-color: red;" class="select new">
  <option style="background-color: green;" value="green">green</option>
  <option style="background-color: yellow;" value="yellow">yellow</option>
  <option style="background-color: blue;" value="blue">blue</option>
  <option style="background-color: red;" value="red">red</option>
</select>

JQuery variant:

var select = $('.select.new');
select.on('change', function() {
  select.css('background-color', select.val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select style="background-color: red;" class="select new">
  <option style="background-color: green;" value="green">green</option>
  <option style="background-color: yellow;" value="yellow">yellow</option>
  <option style="background-color: blue;" value="blue">blue</option>
  <option style="background-color: red;" value="red">red</option>
</select>
Scroll to Top