Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Possible to style select element so style of selected option is shown when dropdown 'closed'?

Given this simple html,

<select id="ddl">
    <option style="background:#0f0">a</option>       
    <option style="background:#f00;">b</option>   
    <option>c</option>
</select>

(http://jsfiddle.net/DxK47/) You can see that each option has it's own background colour.

Unfortunately, when whatever option is selected (causing the dropdownlist to 'close'), the background remains white (or whatever the page default is).

Is it possible to have the background of the selected item be displayed in the dropdownlist after the selection has been made (ideally without using javascript)

like image 445
maxp Avatar asked Sep 26 '12 12:09

maxp


1 Answers

Yes, is possible

JS:

$(function(){
    $("#ddl").on("change", function(){
        $("#ddl").css("background", $("#ddl option:selected").attr("style").replace("background:",""));
    });       
});

jsfiddle: http://jsfiddle.net/SnakeEyes/DxK47/3/

and remove the ; from second option

<option style="background:#f00;">b</option>

to

<option style="background:#f00">b</option>  

Other solution: http://jsfiddle.net/SnakeEyes/DxK47/13/

like image 109
Snake Eyes Avatar answered Sep 20 '22 15:09

Snake Eyes