The problem is how to apply a style on a part of an option.
I have a SELECT like this:
<select id="my_select">
<option value="1">Item 1 <span class="color-red">20 calls</span></option>
<option value="2">Item 2 <span class="color-red">10 calls</span></option>
<option value="2">Item 3 <span class="color-red">30 calls</span></option>
</select>
Browsers don't allow tags within OPTION's and strip them.
So a possible workaround is using HTML entities:
<select id="my_select">
<option value="1">Item 1 <span class="color-red">20 calls</span></option>
<option value="2">Item 2 <span class="color-red">10 calls</span></option>
<option value="2">Item 3 <span class="color-red">30 calls</span></option>
</select>
Now a browser sees the entire content of each OPTION as a text. And here's the Jquery code:
$('#my_select').select2({
minimumResultsForSearch: -1
});
The last thing I stumbled on is replacing the entities "<" and ">" with "<" and ">" symbols respectively AFTER the Select2 is rendered and on a dropdown, to get in the first option box "Item 1" in default black color and "20 calls" in red color (CSS is available: .color-red {color:red;}). And the same for the other option boxes.
I've tried to find the answer in the documentation, but nothing worked. For example,
$('#my_select').select2({
minimumResultsForSearch: -1,
templateResult: function (item) {
item.text.replace (/>/g,'>').replace (/</g,'<');
}
});
Any ideas on how to solve this are greatly appreciated.
templateResultcallback function needs to return the option content. But there is also automatic HTML escaping applied, so you need to return a jQuery object instead of plain HTML, see select2.org/dropdown#built-in-escapingtemplateResult: function (item) { return $('<div>foo <span style="color:red">bar</span></div>'); }