jquery: select options and background color

10,937

Solution 1

//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);
 });
});

Solution 2

selected

$('#events').bind('change', function() {

   var bgc = $(this).find('option:selected').css('background-color');

});

Solution 3

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.

Share:
10,937
Hellnar
Author by

Hellnar

Updated on June 27, 2022

Comments

  • Hellnar
    Hellnar almost 2 years

    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 ?