Skip to content Skip to sidebar Skip to footer

Select2 - Ajax Search - Remember Last Results

I am using Select2 3.5.1. With this plugin I can successfully load remote data. However I am here today to ask a question to improve this search. Here is the step-by-step to unders

Solution 1:

I did read your post once again. I misunderstood you last time.

The solution is here.

   $(document).ready(function () {
        $('#select').select2({
            // this part is responsible for data cachingdataCache: [],
            query: function (q) {
                var obj = this,
                        key = q.term,
                        dataCache = obj.dataCache[key];

                //checking is result in cacheif (dataCache) {
                    q.callback({results: dataCache.results});
                } else {
                    $.ajax({
                        url: 'ajax.php',
                        data: {q: q.term},
                        dataType: 'json',
                        type: 'POST',
                        success: function (data) {
                            //copy data to 'cache'
                            obj.dataCache[key] = data;
                            q.callback({results: data.results});
                        }
                    })
                }
            },
            placeholder: 'Search something',
            width: '333',
            minimumInputLength: 3,
        });
        // this part is responsible for setting last search when select2 is openingvar last_search = '';
        $('#select').on('select2-open', function () {
            if (last_search) {
                $('.select2-search').find('input').val(last_search).trigger('paste');
            }
        });
        $('#select').on('select2-loaded', function () {
            last_search = $('.select2-search').find('input').val();
        });
    });

Solution 2:

This will make another ajax call but with the same query string as before. Uses event select2:closing to save last query string and select2:open to insert the string into the search input and trigger input event.

var lastQueryString = '';

jQuery(".my-select2").select2({
    minimumInputLength: 2,
    placeholder: "Select an option",
    ajax: {
        url: "/example",
        data: function (params) {
            var query = {
                search: params.term
            }
            return query;
        },
        processResults: function (data) {
            return {
                results: JSON.parse(data)
            };
        }
    }
});

jQuery('.my-select2').on('select2:open', function () {
    if (lastQueryString) {
        jQuery('.select2-search').find('input').focus().val(lastQueryString).trigger('input');
    }
});

jQuery('.my-select2').on('select2:closing', function () {
    lastQueryString = jQuery('.select2-search').find('input').val();
});

Post a Comment for "Select2 - Ajax Search - Remember Last Results"