简体   繁体   中英

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:

在此处输入图片说明

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.

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM