Coloured options in a select element using jQuery

Styling form elements can be treacherous territory, as while css should allow this kind of functionality, form handling is increasingly within the remit of the browser (especially across mobile and tablet platforms). However, there are times when plain coloured drop-down lists are not desirable – for example on a status dashboard with many such elements – and this is one method that can be used to change this which appears to fail gracefully.

Let’s say we want to create a select box like the following:

Firstly we define the element:

1
2
3
4
5
6
<select id="select_example">
    <option value="0">---------</option>
    <option value="1">Online</option>
    <option value="2">Offline</option>
    <option value="3">Unknown</option>
</select>

Next we set the background colour of each option, which are children of the select element:

7
8
9
10
11
<script type="text/javascript">
$('select[id=select_example]').children().each(function (){    
    colors = ['white', 'green', 'red', 'orange']
    $(this).attr('style', 'background-color:' + colors[$(this).val()] + ';');
});

However, the background colour of the select element over-rides the background colour of the selected option element, so each time the selected option changes, we should set the select element’s background colour to that of the selected option element:

12
13
14
15
$('select[id=select_example]').change(function (){
    $(this).attr('style', $(this).find('option:selected').attr('style'));
}).change();
</script>

I haven’t tested this across many browsers, but seems to work on the main desktop clients.

5 Comments

  1. Jagtar Singh says:

    Hi Graeme,

    This is a great post and very helpful. However, I am having a little problem – I have realised when you change the values like this:

    ———
    Online
    Offline
    Unknown

    The function stops working – how could I get it to work again while keeping the values, the way I want.

    Thanks a lot for this cool post.

    Kind Regards,
    Jagtar

    • Jagtar Singh says:

      Rather than 0, 1, 2, 3 – I want to use alphabets for values but that makes it stop working. Cheers.

  2. Yuriy says:

    Thanks for help

  3. It’s not good for website!

  4. paramesh says:

    thanq thanq very much bro

Leave a Reply

Your email address will not be published. Required fields are marked *

*

question razz sad evil exclaim smile redface biggrin surprised eek confused cool lol mad twisted rolleyes wink idea arrow neutral cry mrgreen

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>