smolo
smolo

Reputation: 879

Change the background color of the selected option

I have a select object and I'm trying to change the background color of the selected option. So when I select the option "green", the background color has to be changed to green (color information to be taken from the attribute data-color)

The following works but it's not considering attribute data-color and uses just one color (red). I'm fine with a jQuery solution or pure CSS.

https://jsfiddle.net/tomsx/y3ofg0m7/

<select id="colors" size="5" style="height:80px;width:100px">
 <option value="1" data-color="red">red</option>
 <option value="2" data-color="green">green</option>
 <option value="3" data-color="yellow" >yellow</option>
</select>

select:focus option:checked {
  background: red linear-gradient(0deg, red 0%, red 100%);
}

Upvotes: 0

Views: 188

Answers (1)

Doug F
Doug F

Reputation: 884

$("select#colors").change(function () {
  var $thisMenu = $(this);
  $thisMenu.children("option").css("background", "");
  var $thisOption = $thisMenu.children("option:selected");
  var color = $thisOption.data("color");
  $thisOption.css("background", "linear-gradient(0deg, "+ color +" 0%, "+ color +" 100%)");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<select id="colors" class="colors2" size="5" style="height:80px;width:100px">
 <option value="1" data-color="red">red</option>
 <option value="2" data-color="green">green</option>
 <option value="3" data-color="yellow" >yellow</option>
</select>

This works but it changes the colors permanently when selected. Is this what you want or do you want the color to be lost when another option is selected?

Upvotes: 1

Related Questions