I am looking to build multiple html select elements with custom background colors for each option:
<select runat="server" id="select">
<option value="A">White</option>
<option value="B">Red</option>
<option value="C">Yellow</option>
<option value="D">Green</option>
When the website loads, I would like the select element to display only the background color and no text for the selected option. The text (white, red,....) should only be visible when the dropdown is opened.
As the selected value is changed by the user, the background color should change as well while the text should be invisible in the closed dropdown.
It would be really nice if the solution works on most browsers including IE 9/10.
Cheers.
Try this code, works in every browser including IE:
html
<select id="select1" onchange="colourFunction()">
<option class="white" value="A">This should have a WHITE background</option>
<option class="red" value="B">This should have a RED background</option>
<option class="yellow" value="C">This should have a YELLOW background</option>
<option class="green" value="D">This should have a GREEN background</option>
</select>
css
#select1 {width:150px; color:rgba(0, 0, 0, 0);}
#select1:focus, #select1:focus {
color:black;
}
.white {background:white;}
.red {background:red;}
.yellow {background:yellow;}
.green {background:green}
js
function colourFunction() {
var myselect = document.getElementById("select1"),
colour = myselect.options[myselect.selectedIndex].className;
myselect.className = colour;
myselect.blur(); //This just unselects the select list without having to click
somewhere else on the page
}
HTH :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With