Select2, when no option matches, "other" should appear

javascript, jquery, jquery-select2

Solution

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;
}

Demo

Problem

With select2 dropdown, how do I get a default option to appear if no options match the user's typed input? ``` $("something").select2({ formatNoMatches: function(term) { //return a search choice } }); ``` I haven't been able to find anything that really matches this desired functionality within the select2 documentation or Stack Overflow. Edit I'm getting closer with this ``` $("something").select2({ formatNoMatches: function(term) { return "<div class='select2-result-label'><span class='select2-match'></span>Other</div>" } }); ``` But this is pretty hacky off the bat, and also isn't clickable.

Original source