Note that there are some explanatory texts on larger screens.

plurals
  1. POSet background colour of select to selected option in JQuery
    text
    copied!<p>Follow-up to this question: <a href="https://stackoverflow.com/questions/5065167/setting-background-color-of-select-options-in-jquery">Setting background-color of select options in JQuery</a></p> <p>I have a page with multiple select boxes, as per the following:</p> <pre><code>&lt;select name="item-0-status" id="id_item-0-status"&gt; &lt;option value=""&gt;---------&lt;/option&gt; &lt;option value="1"&gt;Online&lt;/option&gt; &lt;option value="2"&gt;Offline&lt;/option&gt; &lt;option value="3"&gt;Unknown&lt;/option&gt; &lt;/select&gt; </code></pre> <p>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.</p> <p>I am allocating colours to the options via the following JQuery code:</p> <pre><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'); } } ); </code></pre> <p>Which works fine.</p> <p>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:</p> <pre><code>$('select[id$=-status][id^=id_item-]').each( function (){ $(this).css('backgroundColor',$('option:selected',this).css('backgroundColor')); } ); </code></pre> <p>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.</p> <p>Any idea how to fix this?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload