tuscan88
tuscan88

Reputation: 5839

jQuery select2 add class to selected items

I want to be able to add a class to selected tags so that I can style them different colours. Is there a way to do this? As an example see the following:

enter image description here

So if I wanted any category tags to be green, any location tags to be blue and any keyword tags to be red how would I do it. I have tried using the templateSelection option like so:

$('select').select2({
    templateSelection: function(item)
    {
        return '<span class="green">' + item.text + '</span>';
    }
});

But the HTML gets escaped so it shows the actual characters instead. Plus this wouldn't add the class to the tag itself anyway.

Upvotes: 2

Views: 948

Answers (1)

Marcos P&#233;rez Gude
Marcos P&#233;rez Gude

Reputation: 22158

You can use that templateSelection and then search if it's a location or a keyword, and add escapeMarkup property:

function template(data, container) {
  if(/Location\:/.test(data.text)) {
     return '<span class="location">'+data.text+'</span>';
  } else {
     return data.text;
  }
}

$('select').select2({
  templateSelection: template,
  escapeMarkup: function(m) { return m; }
});

Please, see it working:

https://jsfiddle.net/cz4ofkvg/1/

Upvotes: 1

Related Questions