jquery-select2jquery-select2-4

Style select options in Select2


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 &lt;span class="color-red"&gt;20 calls&lt;/span&gt;</option>
   <option value="2">Item 2 &lt;span class="color-red"&gt;10 calls&lt;/span&gt;</option>
   <option value="2">Item 3 &lt;span class="color-red"&gt;30 calls&lt;/span&gt;</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 "&lt;" and "&gt;" 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 (/&gt;/g,'>').replace (/&lt;/g,'<');
    }
});

Any ideas on how to solve this are greatly appreciated.


Solution

  • You need to rewrite the escapeMarkup option to allow HTML content.

    In templateResult you inform how and in what way you want to render the content, in this case I use the return of a data-text attribute in each option.

    $('#my_select').select2({
      minimumResultsForSearch: -1,
      escapeMarkup: function(item) {
        return item;
      },
      templateResult: function(item) {
        return $(item.element).data('text');
      }
    });
    .color-red {
      color: #ff0000;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    <select id="my_select" style="width: 100%;">
      <option></option>
      <option value="1" data-text='Item 1 <span class="color-red">20 calls</span>'>Item 1 20 calls</option>
      <option value="2" data-text='Item 2 <span class="color-red">10 calls</span>'>Item 2 10 calls</option>
      <option value="3" data-text='Item 3 <span class="color-red">30 calls</span>'>Item 3 30 calls</option>
    </select>