Greetings, Having a such select box:
<select id="events">
<option value="1" style="background-color:green;">Event 1</option>
<option value="2" style="background-color:yellow;">Event 2</option>
<option value="3" style="background-color:blue;">Event 3</option>
<option value="4" style="background-color:red;">Event 4</option>
</select>
At the initial browser render of this selectbox and each time a selection is done, I want the selectbox "events" to get the background-color of the selected option.
How can this be achieved via jquery or via regular javascript ?
Greetings, Having a such select box:
<select id="events">
<option value="1" style="background-color:green;">Event 1</option>
<option value="2" style="background-color:yellow;">Event 2</option>
<option value="3" style="background-color:blue;">Event 3</option>
<option value="4" style="background-color:red;">Event 4</option>
</select>
At the initial browser render of this selectbox and each time a selection is done, I want the selectbox "events" to get the background-color of the selected option.
How can this be achieved via jquery or via regular javascript ?
Share Improve this question edited Dec 3, 2010 at 11:29 Hellnar asked Dec 3, 2010 at 11:24 HellnarHellnar 64.9k82 gold badges208 silver badges282 bronze badges 1- Can $("form option") be used instead of an ID? Or some method so ALL of your select menus are styled the same? – user1024491 Commented Nov 1, 2011 at 20:49
4 Answers
Reset to default 2//Alert color on initial page load
var bkg = $("#events option:selected").css("background-color");
alert(bkg);
//Handle change event and alert color when selection is done
$(function(){
$("#events").change(function() {
var bkg = $("#events option:selected").css("background-color");
alert(bkg);
});
});
selected
$('#events').bind('change', function() {
var bgc = $(this).find('option:selected').css('background-color');
});
You can do this:
$("#events").change(function() {
$(this).css("backgroundColor",
$(this).find(":selected").css("backgroundColor")
);
}).change();
You can test it out here. But, this won't work in all browsers, especially in IE the <select>
element is notoriously unstyleable (for lack of a better...or real word). It'll work in the browsers that support it and just have no effect in the ones that don't. You may instead wait to style a parent element to give an indicator in all browsers, something like this.
IE friendly way, this has to applied to option
tag.
$(this).html($(this).html());