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();