I'm not sure if this is a mistake or not - in any case there is no open problem related to this behavior in the GitHub tracker problem at the moment.
In most cases, you can correct your behavior. The idea is that the createSearchChoice should be able to determine whether the term refers to the search result or not. But createSearchChoice does not have direct access to search results, so how can we enable this? Well, keeping the last batch of search results inside the results callback.
var lastResults = []; $(...).select2({ ajax: { multiple: true, url: "/echo/json/", dataType: "json", type: "POST", data: function (term, page) { return { json: JSON.stringify({results: [{id: "foo", text:"foo"},{id:"bar", text:"bar"}]}), q: term }; }, results: function (data, page) { lastResults = data.results; return data; } }, createSearchChoice: function (term) { if(lastResults.some(function(r) { return r.text == term })) { return { id: term, text: term }; } else { return { id: term, text: term + " (new)" }; } } });
This code uses Array.some , so you need something better than IE8 (which is the minimum requirement for select2) to run it, but of course you can emulate the behavior.
Look at the action .
There is, however, a fly in maz: this code only works if the search results matching the current search query have already been received.
This should be obvious: if you type very quickly and create a search createSearchChoice that matches an existing tag, but strikes a comma before the search results that include this tag, createSearchChoice will test for the presence of the tag among the previously received search results. If these results do not include the tag, then the tag will be displayed as "new", even if it is not.
Unfortunately, I do not believe that you can do something to prevent this from happening.
Jon May 31 '13 at 13:00 2013-05-31 13:00
source share