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 |
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.
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
Rather than 0, 1, 2, 3 – I want to use alphabets for values but that makes it stop working. Cheers.
Thanks for help
It’s not good for website!
thanq thanq very much bro
It is impressive coding. Printing is also very easy for this coding. Thanks for sharing such a wonderful information.