Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set background colour of select to selected option in JQuery

Tags:

jquery

css

Follow-up to this question: Setting background-color of select options in JQuery

I have a page with multiple select boxes, as per the following:

<select name="item-0-status" id="id_item-0-status">
<option value="">---------</option>
<option value="1">Online</option>
<option value="2">Offline</option>
<option value="3">Unknown</option>
</select>

These are being auto-generated in django, so it is not possible to apply css classes, ids or attributes directly to the options. The select elements have ids of 'item-0-status','item-1-status','item-2-status' etc.

I am allocating colours to the options via the following JQuery code:

$('select[id$=-status][id^=id_item-]').children().each(
        function (){
            if($(this).val() == 0){
                $(this).css('backgroundColor','white');
            }
            if($(this).val() == 1){
                $(this).css('backgroundColor','green');
            }
            if($(this).val() == 2){
                $(this).css('backgroundColor','red');
            }
            if($(this).val() == 3){
                $(this).css('backgroundColor','orange');
            }
        }
    );

Which works fine.

I also want the select elements to have the same background colour as the selected option, which I am trying to achieve using the following:

$('select[id$=-status][id^=id_item-]').each(
        function (){
            $(this).css('backgroundColor',$('option:selected',this).css('backgroundColor'));
        }
    );

However, this just colours the select element in blue (I think it is taking the colour from the hover property rather than the background). This is in Firefox 3.6.8, which for the purposes of this question is the only browser concerned.

Any idea how to fix this?

like image 467
meepmeep Avatar asked Feb 21 '11 15:02

meepmeep


People also ask

How can set background color in JQuery?

To add the background color, we use css() method. The css() method in JQuery is used to change style property of the selected element. The css() in JQuery can be used in different ways. The css() method can be used to check the present value of the property for the selected element.

How can change background color of button click in JQuery?

JavaScript Code:$("div"). on( "click", "button", function( event ) { $(event. delegateTarget ). css( "background-color", "green"); });


3 Answers

Replace the "each" with "change"

$('select[id$=-status][id^=id_item-]').change(
    function (){
        var color = $('option:selected',this).css('background-color');
        $(this).css('background-color',color);
    }
).change();

This works in Chrome.

Also see: http://docs.djangoproject.com/en/dev/ref/contrib/admin/#modeladmin-media-definitions

Custom css in django admin is supported.

And I believe that the correct css attribute is: 'background-color'. backgroundColor is javascript and should be used like this: $(this).css({backgroundColor:color}); But it seems to work anyway so no biggie.

EDIT:

If you want to init the script on page load you can just add .change() behind. See code.

I also tested this in firefox and I also see this strange behavior (blue, wth blue?).

Another EDIT:

Ok, so here is a quick fix for firefox:

$('select[id$=-status][id^=id_item-]').children().each(function (){
    if($(this).val() == 0){
        $(this).attr('style', 'background-color:white;');
    }
    if($(this).val() == 1){
        $(this).attr('style', 'background-color:green;');
    }
    if($(this).val() == 2){
        $(this).attr('style', 'background-color:red;');
    }
    if($(this).val() == 3){
        $(this).attr('style', 'background-color:orange;');
    }
});

$('select[id$=-status][id^=id_item-]').change(function (){
    var style = $(this).find('option:selected').attr('style');
    $(this).attr('style', style);
}).change();

Last EDIT:

You could even to this if you're using css:

<style>
    select option,
    select {
        background-color:white;
    }

    select option[value="1"],
    select.o1
    {
        background-color:green;
    }

    select option[value="2"],
    select.o2
    {
        background-color:red;
    }

    select option[value="3"],
    select.o3
    {
        background-color:orange;
    }
</style>

<script>    
    $('select[id$=-status][id^=id_item-]').change(function (){
        var color = $(this).find('option:selected').val();

        $(this).removeClass('o1 o2 o3').addClass('o' + $(this).find('option:selected').val());
    }).change();
</script>

Yet another edit:

I came across this and saw that I could make it shorter so I did just for fun:

$('select[id$=-status][id^=id_item-]').children().each(function() {    
    var colors = ['white', 'green', 'red', 'orange'];
    $(this).attr('style', 'background-color:' + colors[$(this).val()] + ';');
});
$('select[id$=-status][id^=id_item-]').change(function() {
    $(this).attr('style', $(this).find('option:selected').attr('style'));
}).change();
like image 117
demux Avatar answered Nov 03 '22 04:11

demux


$("select[id$=-status][id^=id_item-]").change(function (){
    var style = $(this).find('option:selected').attr('style');
    $(this).attr('style', style);
    $("select[id$=-status][id^=id_item-] option:selected").each(function () {
            $(this).attr('style', style);
          });
}).trigger('change');

Add style to you HTML code, use trigger don't forget to load this in your $(document).ready(function(){} Also don't forget to put this code after populating your Select box from the DB

like image 33
Ahmed Mohamed Avatar answered Nov 03 '22 03:11

Ahmed Mohamed


I like @Arnar Yngvason's answer but I'll add this to the mix. This solution uses CSS classes so the styles can be easily changed without breaking the rest of the code.

Html

<select>
    <option class="Red">Red</option>
    <option class="Blue">Blue</option>
    <option class="Green">Green</option>
    <option class="Yellow">Yellow</option>
</select>
<div id="output"></div>

CSS

.Red{background-color:#ff0000;}
.Blue{background-color:#0000ff;}
.Green{background-color:#00ff00;}
.Yellow{background-color:#ffff00;}

JavaScript

$("select").change(function(){
    $(this).removeClass($(this).attr('class'))
           .addClass($(":selected",this).attr('class')); 
    /*If you want to keep some classes just add them back here*/
    //Optional: $(this).addClass("Classes that should always be on the select");

});

 $("select").change(function() {
   $(this).removeClass($(this).attr('class'))
     .addClass($(":selected", this).attr('class'));
   /*If you want to keep some classes just add them back here*/
   //Optional: $(this).addClass("Classes that should always be on the select");

 });
    .Red {
      background-color: #ff0000;
    }
    .Blue {
      background-color: #0000ff;
    }
    .Green {
      background-color: #00ff00;
    }
    .Yellow {
      background-color: #ffff00;
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
  <option class="Red">Red</option>
  <option class="Blue">Blue</option>
  <option class="Green">Green</option>
  <option class="Yellow">Yellow</option>
</select>
<div id="output"></div>

JSFiddle

I've tested this on FireFox 31, IE 11 and Chrome 37

like image 2
Dan Avatar answered Nov 03 '22 03:11

Dan