How to add Custom message into Select2

This tutorial will illustrate to you, how to add a user-defined message into the select2 control. I am using the jQuery Select2 plugin.

The Default message of select2 is ‘No matches found’. Sometimes we need to add a custom message for select2. I will share the script for the set custom message as well as fire an event on this message.

Also checkout other tutorials of select2,

Step 1: We will add custom option for the default option.

html += "Add New Number";

The above code will show you the ‘Add New Number’ text when you will render select2.

Step 2: Now we will add condition to show the above option into the select2 dropdown list, when the search string does not found in select2, then we will show ‘Add New Number’ instead of the default message.

matcher: function(term, text) {
   return text === 'Add New Number' || $.fn.select2.defaults.matcher.apply(this, arguments);
}

Step 3: Remove this option at the time of select2 binding.

matcher: function(term, text) {
  return text === 'Add New Number' || $.fn.select2.defaults.matcher.apply(this, arguments);
}

So ‘Add New Number’ will not show when the first time select2 render, it will show when the matching character does not find.

sortResults: function(results) {
	if (results.length > 1) results.pop();
	return results;
}

Step 4: The Full code of select2 with a custom option.

jQuery("#selectId").select2({
	width: 'element',
	matcher: function(term, text) {
		return text === 'Add New Number' || $.fn.select2.defaults.matcher.apply(this, arguments);
				},
	sortResults: function(results) {
	   if (results.length > 1) results.pop();
		return results;
	}
});

Step 5: Result.

custom search message

Demo & Download Source Code

4 thoughts on “How to add Custom message into Select2

    • Hi Dung,
      Its working fine,in this tut we are overwriting default message and adding our pre defined message when no option has been found.

      What do u want?

Leave a Reply

Your email address will not be published. Required fields are marked *