DisgruntledGoat DisgruntledGoat - 1 month ago 7
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></option>
<option value="1">Item 1</option>
<option value="2" class="deleted">Item 2</option>
<option value="3">Item 3</option>
</select>


And it's initialised like this:

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


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

The only thing I see that comes close is the
templateResult
option, where I can check for
opt.element.className
. 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
find()
function, but that only gets the original
<option>
elements, not the
<li>
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

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.

$("select").select2({
  templateResult: function (data, container) {
    if (data.element) {
      $(container).addClass($(data.element).attr("class"));
    }
    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>
</select>