SHARE
TWEET

Autocomplete JS

Grork Feb 17th, 2017 (edited) 66 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. $('#autocomplete').autocomplete({
  2.     source: function(req, res) {
  3.     var loadFromCache = autocomplete_from_cache(req.term);
  4.     // Return cache results, if there are
  5.     if (loadFromCache) {
  6.         return res(loadFromCache);
  7.     }
  8.    
  9.         $.get('/autocomplete/company/' + req.term.replace(/ /g, '+'), function(r) {
  10.         autocomplete_add_cache(req.term, r);
  11.         return res(r);
  12.         }, 'json');
  13.     },
  14.     minLength: 2,
  15.     select: function (e, ui) {
  16.         $(e.target).val(ui.item.name);
  17.         return false;
  18.     }
  19. }).autocomplete('instance')._renderItem = function (ul, item) {
  20.     return $('<li>')
  21.         .append('<a>' + item.name + '</a>')
  22.         .appendTo(ul);
  23. };
  24.  
  25. function autocomplete_add_cache(term, results) {
  26.     var expiry = new Date();
  27.     expiry.setMonth(expiry.getMonth() + 1);
  28.     expiry = expiry.getTime();
  29.  
  30.     localStorage.setItem('autocomplete-company-' + encodeURI(term.toLowerCase()), JSON.stringify({ expiry: expiry, results: results }));
  31. }
  32.  
  33. function autocomplete_from_cache(term) {
  34.     // Check for local storage
  35.     if (typeof localStorage !== 'undefined') {
  36.         try {
  37.             localStorage.setItem('feature_test', 'yes');
  38.             if (localStorage.getItem('feature_test') === 'yes') {
  39.                 localStorage.removeItem('feature_test');
  40.             } else {
  41.                 return false;
  42.             }
  43.         } catch(e) {
  44.             return false;
  45.         }
  46.     } else {
  47.         return false;
  48.     }
  49.  
  50.     // Check if item exists
  51.     if (localStorage.getItem('autocomplete-' + type + '-' + encodeURI(term.toLowerCase())) === null)
  52.         return false;
  53.  
  54.     var autocomplete = JSON.parse(localStorage.getItem('autocomplete-company-' + encodeURI(term.toLowerCase())));
  55.     // Check if is expired
  56.     if (autocomplete.expiry < new Date().getTime()) {
  57.         return false;
  58.     }
  59.  
  60.     return autocomplete.results;
  61. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Top