Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 871
varatis Avatar asked Jul 30 '13 14:07

varatis


People also ask

Why select2 is not working?

Select2 does not function properly when I use it inside a Bootstrap modal. This issue occurs because Bootstrap modals tend to steal focus from other elements outside of the modal. Since by default, Select2 attaches the dropdown menu to the <body> element, it is considered "outside of the modal".

How do I create a select2 dynamically?

Select2 jQuery plugin is easy to add on the <select > element. Need to call the select2() method on the selector to initialize. If you adding select2 on a class or select element and when you add an element dynamically then select2 is not initialized on that element.

How do I make select2 empty?

In order to clear the selection of those values which are selected using a Select2 drop down,we can use the empty() function. The dropdown can be reset using Jquery. $("#select2_example"). empty();


1 Answers

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

like image 139
Fabrício Matté Avatar answered Sep 23 '22 15:09

Fabrício Matté