Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
69
rated 0 times [  72] [ 3]  / answers: 1 / hits: 18959  / 11 Years ago, tue, july 30, 2013, 12:00:00

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.


More From » jquery

 Answers
40

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


[#76647] Monday, July 29, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
devinjadong

Total Points: 711
Total Questions: 117
Total Answers: 100

Location: Andorra
Member since Sat, May 27, 2023
1 Year ago
devinjadong questions
Thu, Feb 17, 22, 00:00, 2 Years ago
Wed, Dec 8, 21, 00:00, 2 Years ago
Tue, Oct 27, 20, 00:00, 4 Years ago
Fri, Oct 18, 19, 00:00, 5 Years ago
;