Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

html select with different background color for every option that works properly in every browser?

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.

like image 344
Jagtar Avatar asked May 13 '13 12:05

Jagtar


1 Answers

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 :)

like image 79
Singh Avatar answered Oct 03 '22 17:10

Singh