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 add custom option for 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.

custom search message

Here I am sharing source code and live demo.
  • http://www.androprogrammer.com robert

    Hey in source code the code is different then above one. have you checked it ?
    in it you have used flexigrid not select 2.

    • http://phpflow.com Parvez

      Thanks robert,
      i have changed download url.

  • http://sanlaocai.com Dung Vu

    Demo not working when click on “Add New Number”. Add New Number is selected on value.

    • http://phpflow.com Parvez

      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?