Mark new tag in select2?

javascript, jquery, jquery-select2

Solution

Thanks for posting (and answering) the question! I think I've found a simpler way to solve this:

...
createSearchChoice:function(term, data) {
    if ($(data).filter(function() {
        return this.text.localeCompare(term) === 0;
    }).length === 0) {
        return {id:term, text: term, isNew: true};
    }
},
formatResult: function(term) {
    if (term.isNew) {
        return '<span class="label label-important">New</span> ' + term.text;
    }
    else {
        return term.text;
    }
},
...

You can return any object from the `createSearchChoice()` function, so just add in a field telling `formatResult()` that it's a new item.

This way, the text of the returned item is just the text you want, and `formatResult()` is a lot simpler.

Problem

I am using select2, I have set it up so I can add a new tag if it does not exist, I am also using twitter bootstrap, If a tag does not exist I want to mark it as a new tag, to do so I prepend the text with `'<span class="label label-important">New</span> '` this as my select2 initializer. ``` $('#newVideoCategory').select2({ placeholder: 'Select a category...', data: categories, createSearchChoice: function (term, data) { if ($(data).filter(function () { return this.text.localeCompare(term) === 0; }).length === 0) { return {id: term, text: '<span class="label label-important">New</span> ' + term}; } }, initSelection: function (element, callback) { $(categories).each(function () { if (this.id == element.val()) { callback(this); return; } }) } }) ``` Now this works great Unless what I have entered for the tag exists as part of the markup for that label From what I have gathered I need to overwrite either the `formatResult`, `formatSelection`, or `matcher`. That's what I got from the documentation, but I don't understand how I need to alter it.

Original source