Reputation: 64793
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 ?
Upvotes: 3
Views: 11515
Reputation:
IE friendly way, this has to applied to option
tag.
$(this).html($(this).html());
Upvotes: 0
Reputation: 630379
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.
Upvotes: 1
Reputation: 14967
$('#events').bind('change', function() {
var bgc = $(this).find('option:selected').css('background-color');
});
Upvotes: 1
Reputation: 1046
//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);
});
});
Upvotes: 2