Select2, when no option matches, "other" should appear
To complement on @vararis's answer:
Select2 attached to a <select>
element does not allow for custom createSearchChoice
nor query
functions, hence we will need to manually add an option element (I'll add it as the last option of the element so we can easily .pop
it out of the results set):
<select>
...
<option value="0">Other</option>
</select>
Then pass a custom matcher
function so that this "Other" option is always matched.
NOTE: Select2 3.4+ uses a different default matcher than the one currently shown in the documentation, this new one has a call to the stripDiacritics
function so that a
matches á
for instance. Therefore I'll apply the default matcher
that comes with the Select2 version included in the page to apply its default matching algorithm to any option that's not the "Other" option:
matcher: function(term, text) {
return text==='Other' || $.fn.select2.defaults.matcher.apply(this, arguments);
},
Finally, we need to remove the "Other" option from the results set when there's any result besides the "Other" result (which is initially always in the results set):
sortResults: function(results) {
if (results.length > 1) results.pop();
return results;
}