DisgruntledGoat DisgruntledGoat - 1 year ago 85
jQuery Question

How to pass <option> attributes to select2?

I'm using Select2 4.0. I have a list of options, some of which are "deleted" and I want to signify which are which. My select element is like this:

<style>.deleted { color: red; }</style>

<select name="itemid" id="item-list" tabindex="1">
<option value="1">Item 1</option>
<option value="2" class="deleted">Item 2</option>
<option value="3">Item 3</option>

And it's initialised like this:

<script src="/static/js/select2.min.js"></script>
$(function() {
placeholder: 'Select item'

However, on the resulting HTML code that select2 generates I don't see any way to reference that class. Also tried a
attribute on the option, with no luck.

The only thing I see that comes close is the
option, where I can check for
. But I cannot see how to access the select2 option from there. Anyway that callback runs on every single search which is not at all what I want.

Is there some other way to style particular options in Select2?

UPDATE: as noted in the comments there is a
function, but that only gets the original
elements, not the
elements that select2 generates. Here's what I tried:

var sel2 = $("#item-list").select2({
placeholder: 'Select item'

sel2.find('.deleted').each(function() {
$(this).css('color', 'red');

Answer Source

As of Select2 4.0.1 (just released), you can transfer classes with the templateResult option. The first parameter is the data object being displayed, and the second argument is the container that it will be displayed in.

  templateResult: function (data, container) {
    if (data.element) {
    return data.text;
.yellow { background-color: yellow; }
.blue { background-color: blue }
.green { background-color: green; }
<link href="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/css/select2.css" rel="stylesheet"/>

<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/js/select2.js"></script>

<select class="select2">
  <option value="AL" class="yellow">Alabama</option>
  <option value="AK" class="blue">Alaska</option>
  <option value="AZ" class="green">Arizona</option>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download