The different options of the html select form field show the correct 'colors' of my options as the background-color.
But when one option is selected and thus the select element is shown 'collapsed' it shows a default white background.
What is a clean way to update the background of the select box to the one of the option ?
<select>
<option style="background-color: #CDBA88">RAL:1000</option>
<option style="background-color: #D0B084">RAL:1001</option>
<option style="background-color: #D2AA6D">RAL:1002</option>
<option style="background-color: #F9A800">RAL:1003</option>
<option style="background-color: #E49E00">RAL:1004</option>
</select>
CodePudding user response:
You have to use Javascript as well. So, in a nutshell, on onchange
event, you have to assign a function that sets background color to <select>
component.
Here is a working snippet of what I mean:
var selectBox = document.getElementById('select-box');
function applyBackgroundColor() {
// Check if DOM element exists, otherwise return
if (!selectBox) {
return;
}
selectBox.style.backgroundColor = selectBox.value;
}
selectBox.onchange = applyBackgroundColor;
<select id="select-box">
<option value="#cdba88" style="background-color: #cdba88">RAL:1000</option>
<option value="#d0b084" style="background-color: #d0b084">RAL:1001</option>
<option value="#d2aa6d" style="background-color: #d2aa6d">RAL:1002</option>
<option value="#f9a800" style="background-color: #f9a800">RAL:1003</option>
<option value="#e49e00" style="background-color: #e49e00">RAL:1004</option>
</select>