melvnberd
melvnberd

Reputation: 3163

how to invoke "if no search result" on select2?

Good day,

How can I invoke the "no search result" on select2? for example, I want to add an event listener to my select2 text box but only when there is no result found?

here is my js code:

$("#textBoxId").select2({
    placeholder: 'Select a product',
    formatResult: productFormatResult,
    formatSelection: productFormatSelection,
    dropdownClass: 'bigdrop',
    escapeMarkup: function(m) { return m; },
    formatNoMatches: function( term ) {
    return "<li class='select2-no-results'>"+"No results found.<button class='btn btn-success pull-right btn-xs' onClick='modal()'>Add New Item</button></li>";
    },
    minimumInputLength:1,
    ajax: {
        url: '/api/productSearch',
        dataType: 'json',
        data: function(term, page) {
            return {
                q: term
            };  
        },  
        results: function(data, page) {
            return {results:data};
        }   
    }   
});

I tried adding :

formatNoMatches: function( term ) {
      $('.select2-input').on('keyup', function(e) {
         if(e.keyCode === 13) 
           {
            $("#modalAdd").modal();
           }
      });
    return "<li class='select2-no-results'>"+"No results found.<button class='btn btn-success pull-right btn-xs' onClick='modal()'>Add New Item</button></li>";
    },

And it worked, the modal shows when I press "enter key", but even if I dont search anything, when I press enter key, the modal still shows.

what I want to attain is that, when there is "no result found" then I can open my modal form just by pressing the "enter" key instead of clicking the link so that the modal will be opened.. Thank you very much for the help! Have a Nice day!

Upvotes: 2

Views: 6492

Answers (2)

C&#233;sar Augusto
C&#233;sar Augusto

Reputation: 734

Replace result: function(data, page) by processResults: function(data, page) it´s Work

Upvotes: 0

melvnberd
melvnberd

Reputation: 3163

by searching some alternatives I came up to this code, I just unbind the keyup listener event once the modal was being called here my code:

    formatNoMatches: function( term ) {
      var flag = 1;
      $('.select2-input').on('keyup', function(e) {
         if(e.keyCode === 13) 
           {
            $("#modalAdd").modal();
            $(".select2-input").unbind( "keyup" );
           }
      });
    return "<li class='select2-no-results'>"+"No results found.<button class='btn btn-success pull-right btn-xs' onClick='modal()'>Add New Item</button></li>";
    }

Upvotes: 2

Related Questions