Search in dropdown


this is the first time that i use “Select2”.
I have a select like this:
<select name="models" id="models> <option></option> <option id="single-model-2601" value="2601">Samsung G928F Galaxy S6 Edge Plus</option> <option id="single-model-2712" value="2712">Samsung G930F Galaxy S7</option> <option id="single-model-2713" value="2713">Samsung G935F Galaxy S7 EDGE</option> <option id="single-model-2872" value="2872">Samsung G950 Galaxy S8</option> </select>

with this javascript code:
// In your Javascript (external .js resource or tag)
jQuery(document).ready(function() {

		minimumInputLength: 2,
		placeholder: "please select model",
		templateResult: formatModels
	function formatModels (state) {
	  	if (! {
			return state.text;
		var originalOption = jQuery(state.element);
		var $state = jQuery('<div class="device-cantainer<span>'+ + '</span><span>' + state.txt + '</span></div>');
		return $state;

All works fine!
I have only one question about search function:
for example i have to search the phone “Samsung G950 Galaxy S8”;
in search field if i write “Galaxy s8” or “s8” or “g950” it works,
but if i write “Samsung s8” it doesn’t work … i think because words are not consecutive.

Is it possible to solve?
Thank you.

ps. I congratulate the developers for the excellent script.


Yes, it is possible. You need to implement a custom matcher. This will allow you to write custom logic to match items.

The built-in matching algorithm is a case-insensitive substring match. You would need to do something like break the user’s input into separate “terms” (split the user’s input on spaces) and then check whether all of those terms appear in the item’s text. If the order of the user’s search terms is important (for example, “Samsung s8” matches, but “s8 Samsung” doesn’t, then you would also need to include logic so that the first term must match earlier in the item’s text than the second term (and so on if the user enters more than two terms).

I have implemented something similar for a work project, so I know that the custom matcher approach works.


Hi John,
thank you so much for suggestions!!!
searching online about, i found this great solution for " [Non Adjacent Keywords]".
I post the link:

bye :slight_smile:


Hi, guardino–

I’m glad I could help. If you don’t mind, please Like my answer (click the heart icon). It helps people on this site know that they can trust my recommendations.

I have given you a Like, too.