1

Here's a reference image for my question.

This

I have a select box in HTML with colors as seen in the image above and the code below. Using CSS, I have classes that make the various option elements colored. How can I also make the selected items the same color?

In the picture, red is selected but the background of the selected item is still white. Also, is there a way to disable the hover-over effect? See how when the item labeled orange is hovered over that it's highlighted blue? (NOTE: I have used JavaScript and jQuery to put items in the selector after I press a button.)

<div class="selection">
    <select id="color">
        <option class="selectionpurple" value="purple">purple</option>
        <option class="selectionblue" value="blue">blue</option>
        <option class="selectionred" value="red">red</option>
        <option class="selectiongreen" value="green">green</option>
        <option class="selectionorange" value="orange">orange</option>
    </select>
</div>
fourpastmidnight
  • 4,032
  • 1
  • 35
  • 48
swaffelay
  • 323
  • 2
  • 10
  • https://stackoverflow.com/questions/676324/div-background-color-to-change-onhover refer this – Prachi May 17 '18 at 16:42
  • It is a long road. You want to get the `value` from the `option`. Then you reference that to a `color`. That you apply to the `items`. %)P – deEr. May 17 '18 at 16:46

2 Answers2

0

you can use jquery change() function to achieve this. change() run every time when you select an option. you need just take a value of selected option and using jquery css() function apply that style to select.

var selected = $("select option:selected").val();
$('select').css('backgroundColor', selected);

$( "select" ).change(function () {
    console.log($(this).val());
    $('select').css('backgroundColor', $(this).val())
})
.red {
background-color : red;
}
.blue {
background-color : blue;
}
.green {
background-color : green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="text"> 
  <option value="red" class="red" selected>red</option> 
  <option value="blue" class="blue">blue</option>
  <option value="green" class="green">green</option>
</select>
patelarpan
  • 7,188
  • 2
  • 20
  • 25
0

var selected = $("select option:selected").val();
$('select').css('backgroundColor', selected);

$( "select" ).change(function () {
    console.log($(this).val());
    $('select').css('backgroundColor', $(this).val())
})
.red {
background-color : red;
}
.blue {
background-color : blue;
}
.green {
background-color : green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="text"> 
  <option value="red" class="red" selected>red</option> 
  <option value="blue" class="blue">blue</option>
  <option value="green" class="green">green</option>
</select>
swaffelay
  • 323
  • 2
  • 10