admin管理员组文章数量:1312658
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());
本文标签: javascriptjquery select options and background colorStack Overflow
版权声明:本文标题:javascript - jquery: select options and background color - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741916815a2404780.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论