1

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.

How can I add css colours to the options using the id of the select element?

I have tried to follow the code here: How do you select a particular option in a SELECT element in jQuery?

This has lead me to do, e.g. the following for setting 'offline' options to red:

$('select[id$=-status][id^=id_item-]').children().find('option[value="2"]').css('background-color','#FF0000');

but this has no effect.

How can I make this work? I realise support for this varies between browsers, but this is not an issue. For the purposes of this question working in Firefox 3.6 is enough.

Community
  • 1
  • 1
meepmeep
  • 3,018
  • 7
  • 33
  • 47

2 Answers2

1

You have a typo.

It should be background-color. You have missed 'r'

adarshr
  • 61,315
  • 23
  • 138
  • 167
1

Something like should work though note that I am not so sure.

$(function(){   

$('#id_item-0-status').children().each(
        function (){
            if($(this).val() == 2){
                $(this).css({'background':'red'});
            }
        }
);

})  
S L
  • 14,262
  • 17
  • 77
  • 116
  • this works, thanks, but any idea how I can now set the background colour of the selects to that of the selected options? I've tried $('select[id$=-status][id^=id_item-]').css({'background':$('option:selected',this).css('background')}); – meepmeep Feb 21 '11 at 13:46
  • or,better (but still not working):$('select[id$=-status][id^=id_item-]').each(function(){$(this).css({'background':$('option:selected',this).css('background')});}); – meepmeep Feb 21 '11 at 13:53
  • never mind, I have asked this as a separate question http://stackoverflow.com/questions/5068087/set-background-colour-of-select-to-selected-option-in-jquery – meepmeep Feb 21 '11 at 15:55