Skip to content

Instantly share code, notes, and snippets.

@rjhilgefort
Forked from mrgcohen/Readme.md
Last active November 9, 2022 22:17
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rjhilgefort/6234462 to your computer and use it in GitHub Desktop.
Save rjhilgefort/6234462 to your computer and use it in GitHub Desktop.

Requirements

  • bootstrap with typeahead
  • jquery

Explanation

This will use bootstrap with typeahead to create an autocomplete search. It shouldn't search until user is done their thought. Aka - fast typers. Right now set to 300ms.

Also caches content from server so you don't make the same call over and over again.

RJH Edits

  • Made this into a reusable function.
  • Store the cache result in association with the $obj passed into the function.
function typeaheadAjax ($obj, path)
{
// use this hash to cache search results
$obj.query_cache = {};
$obj.typeahead({
source:function (query, process)
{
// if query is in cache use cached return
if($obj.query_cache[query]){
return process($obj.query_cache[query]);
}
//if searching is defined, it hasn't been executed yet but the user typed something else
if( typeof searching != "undefined") {
clearTimeout(searching);
process([]);
}
//define a timeout to wait 300ms before searching
searching = setTimeout(function()
{
return $.getJSON(
path,
{ query: query },
function (data) {
// save result to cache, remove next line if you don't want to use cache
$obj.query_cache[query] = data;
// only search if stop typing for 300ms aka fast typers
return process(data);
}
);
}, 300);
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment