Skip to content

Instantly share code, notes, and snippets.

@mrgcohen
Last active November 9, 2022 22:17
Show Gist options
  • Star 31 You must be signed in to star a gist
  • Fork 19 You must be signed in to fork a gist
  • Save mrgcohen/5062352 to your computer and use it in GitHub Desktop.
Save mrgcohen/5062352 to your computer and use it in GitHub Desktop.
Twitter Bootstrap Typeahead autocomplete example

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.

$(document).ready(function(){
// use this hash to cache search results
window.query_cache = {};
$('#search-input').typeahead({
source:function(query,process){
// if in cache use cached value, if don't wanto use cache remove this if statement
if(query_cache[query]){
process(query_cache[query]);
return;
}
if( typeof searching != "undefined") {
clearTimeout(searching);
process([]);
}
searching = setTimeout(function() {
return $.getJSON(
"search.json",
{ q:query },
function(data){
// save result to cache, remove next line if you don't want to use cache
query_cache[query] = data;
// only search if stop typing for 300ms aka fast typers
return process(data);
}
);
}, 300); // 300 ms
}
});
});
Search <input type="text" name="query" id="search-input"/>
@fer-ri
Copy link

fer-ri commented Mar 2, 2013

This is what i need, work with native bootstrap :)
Thanks, forked it :)

@waqarbaig
Copy link

Thanks! that helped a lot.

@roman-1983
Copy link

Sparar.de says thanks for that!

@rjhilgefort
Copy link

Thanks for the gist. I forked it to tweak a little bit...

  • Made this into a reusable function
  • Store the cache results in association with the $obj passed into the function

https://gist.github.com/rjhilgefort/6234462

@parisnakitakejser
Copy link

Thanks a lot, i use this code to fix my problem close on what you link to ;) this will be faster and you can do more like this if you want more data into this typeahead.

$input.keydown(function(){
$input.typeahead({source:function(query, process){
$.post('{url}',{
'q' : query
},function(data){
return process(data.contentList);
},'json');
}
});
})

@srv89
Copy link

srv89 commented Dec 6, 2016

How to make it work with a dynamic input field. Currently it doesn't seem to work with a dynamic field with is already present on the page

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