Styling part of the OPTION text

Viewed 45430

I have a SELECT list with several OPTION elements. Here is my naive approach to styling part of the option text:

<select name="color">
<option value="0">red <span style="font-weight: bold;">SLOW</span></option>
<option value="1">blue <span style="font-weight: bold;">SLOWER</span></option>
<option value="2">green <span style="font-weight: bold;">SLOWEST</span></option>
</select>

This does not work: the browser does not like a SPAN element inside the OPTION element.

Is there some other way to style part of an OPTION element's text?

6 Answers

This is more like an answer / workaround to the question closed as a duplicate on other tags rather than styling in particular for <options>.

If you don't mind getting dirty with JavaScript, Select2 provides a very concise way to achieve that. It does use lists for that as well.

Here is HTML

<select id="e1" style="width:300px">
  <option value="AL" data-badge="3">Alabama</option>
  <option value="WY">Wyoming</option>
</select>

And here is CoffeeScript

$("#e1").select2
  theme: "bootstrap"
  templateResult: (data) ->
    badge = $(data.element).data('badge')
    if badge
      return $(document.createTextNode(data.text)).add($('<span class="badge pull-right">').text(badge))
    data.text

And here is JSFiddle.

Rendered result

Related