Php Flow » Misc

How to add Custom message into Select2

In this tutorial i will tell you how to add user defined message into select2 control.The Default message of select2 is ‘No matches found’.Sometimes we need to add custom message for select2.In this tutorial i will share script for set custom message as well as fire an event on this message.

Step 1: we will ad custom option foe default option.

1
html += "<option value='0'>Add New Number</option>";

Above code will show you ‘Add New Number’ text when you will render select2.

Step 2: Now we will add condition to show above option, when the search match string does not found instead of default message.

1
2
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.

1
2
3
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.

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

Step 4: Full code.

1
2
3
4
5
6
7
8
9
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.

cusome search message

Did you enjoy this article? Share it!

About the Author:

Hi, This is Parvez Alam from India. I am software developer with 4 years’ experience in web development. I have submitted articles on PHP, Mysql, Magento,CSS, HTML, jQuery, web designing and social API. You can subscribe to my blog via RSS/Twitter/Google plus and Facebook. parvez1487(at)gmail(dot)com

Random Posts

Leave a Reply

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

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>