Skip to content

Instantly share code, notes, and snippets.

@M-Yankov
Last active October 16, 2019 05:34
Show Gist options
  • Save M-Yankov/1451da29eddbd1bc71c0975af80e63ae to your computer and use it in GitHub Desktop.
Save M-Yankov/1451da29eddbd1bc71c0975af80e63ae to your computer and use it in GitHub Desktop.
select2 dropdown: When loading results with ajax, load them once. (the results are always the same)
var s2data = $allUnitsSelect.select2({
ajax: {
url: '/GetValues',
dataType: 'json',
data: function (params) {
var query = {
text: text,
}
return query;
},
processResults: function (responseValues) {
var listItems = mapResponseData(responseValues);
this.options.set('cacheDataSource', listItems);
return { results: listItems };
}
},
cacheDataSource: [],
allowClear: true,
placeholder: 'Select Values ...',
width: '100%',
}).data('select2');
s2data.dataAdapter.query = function (params, callback) {
var cacheDataSource = this.options.get('cacheDataSource');
if (cacheDataSource && cacheDataSource.length > 0) {
callback({ results: cacheDataSource });
}
else {
// call the original logic
var ajaxAdapterFunc = jQuery.fn.select2.amd.require('select2/data/ajax');
var ajaxAdapter = new ajaxAdapterFunc(this.$element, this.options);
ajaxAdapter.query(params, callback);
}
}
@nj-git
Copy link

nj-git commented Oct 15, 2019

I had to update the code, else search stopped working

s2data.dataAdapter.query = function (params, callback) {
        var cacheDataSource = this.options.get('cacheDataSource');
        if (cacheDataSource && cacheDataSource.length > 0) {
            callback(
                {
                    results: cacheDataSource.filter(function (b) {return b.text && b.text.toLowerCase().includes(params.term.toLowerCase()); })
                });
        }
        else {
            var ajaxAdapterFunc = jQuery.fn.select2.amd.require('select2/data/ajax');
            var ajaxAdapter = new ajaxAdapterFunc(this.$element, this.options);
            ajaxAdapter.query(params, callback);
        }
    }

@M-Yankov
Copy link
Author

Hi @nj-git, nice catch.
After working with another dropdown libraries (in react) and hitting a lot of issues, be sure to handle the diacritics search. What I mean is when you have Français in the options and type Franc the search to return the options. I think this is enabled by default. Source

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment