4

I have a Select2 input which I use to search (remote data). Currently, it works like this:

when user types 1 one more characters we trigger search automatically

Now, the fun part:

I need to add following behaviour:

when user focus on in this input and just hits Enter button, I need to trigger search with one character '*' BUT without actually writing that character in the input.

It should just send search request with character * but input should stay empty.

Is that even possible without messing Select2 code?

My code:

$("#account").select2({
    language: "en",
    ajax: {
        url: window.urls.ajax_account_search,
        dataType: 'json',
        delay: 500,
        data: function(params){
            console.log(params);
            return {
                query: params.term,
                page: params.page
            }
        },
        processResults: function(data, params){
            return {
                results: data.items
            }
        },
        cache: true
    },
    escapeMarkup: function(m) { return m; },
    templateResult: formatSearchResult,
    templateSelection: formatSearchSelection,
    minimumInputLength: 1
});
dease
  • 2,975
  • 13
  • 39
  • 75

1 Answers1

0

Instead of triggering the search on enter (with * being sent), you can just send * when there is no search term present. This also means dropping the minimumInputLength requirement, but that seems to line up with what you are looking for.

$("#account").select2({
    language: "en",
    ajax: {
        url: window.urls.ajax_account_search,
        dataType: 'json',
        delay: 500,
        data: function(params){
            return {
                query: params.term || '*', // send * if there is no term
                page: params.page
            }
        },
        processResults: function(data, params){
            return {
                results: data.items
            }
        },
        cache: true
    },
    escapeMarkup: function(m) { return m; },
    templateResult: formatSearchResult,
    templateSelection: formatSearchSelection
});
Kevin Brown-Silva
  • 40,873
  • 40
  • 203
  • 237