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:
Next we set the background colour of each option, which are children of the select element:
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:
I haven’t tested this across many browsers, but seems to work on the main desktop clients.