How to postpone selection-2, so that it waits some time after the user enters data

I know that the above can be achieved using quietMillis in an AJAX call, but I use a query to cache data. And here I can not defer AJAX call. Below is the code

$('#AssetType').select2({ cacheDataSource: [], placeholder: ' ', quietMillis: 3000, query: function q(query) { self = this; var key = query.term; var cacheData = self.cacheDataSource[key]; if (cacheData) { query.callback({ results: $.map(cacheData, function (item) { return { text: item.LongDescription, id: item.AssetTypeID } }) }); return; } else { $.ajax({ url: 'http://localhost:52377/api/reference/asset/types/' + key, dataType: 'json', type: 'GET', quietMillis: 3000, //data: function (query) { // return { assetType: query.term, }; //}, success: function (data) { self.cacheDataSource[key] = data; query.callback({ results: $.map(data, function (item) { return { text: item.LongDescription, id: item.AssetTypeID } }) }); }, cache: true }) } } }); 

Is there any work to delay an AJAX call so that the AJAX call does not start for every keystroke? The reason for using the β€œrequest” is caching, which is not possible by simply setting the cache to true in an AJAX call.

+5
source share
3 answers

According to select2 documentation , you can do this easily.

The request is triggered every time I press a key, can I delay this?

By default, Select2 launches a new AJAX request whenever a user changes their search request. You can set a time limit for debouncing requests using the ajax.delay parameter.

This will cause Select2 to wait 250 milliseconds before sending the request to your API.

 $('select').select2({ ajax: { url: '/example/api', delay: 250 } }); 
+5
source

I found a way to delay the launch. I used the implementation of the debounce function in underscore.js. Now the code will look like this:

 query: debounce(function q(query) {.. ..... }, 350), 

Hope this helps someone.

+2
source

Select2 (4.0.3) has an undocumented option: minimumInputLength

This option will prompt the user to fill in the minimum number of characters and then start the selection.

0
source

All Articles