Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
jQuery Autocomplete
<!DOCTYPE html>
<title>jQuery Autocomplete</title>
#res {
margin: 0px;
padding-left: 0px;
width: 150px;
#res li {
list-style-type: none;
#res li:hover {
background: #110D3B;
color: #FFF;
cursor: pointer;
<script src=""></script>
var people = ['Peter Bishop', 'Nicholas Brody', 'Gregory House', 'Hank Lawson', 'Tyrion Lannister', 'Nucky Thompson'];
var cache = {};
var drew = false;
$("#search").on("keyup", function(event){
var query = $("#search").val()
if($("#search").val().length > 2){
//Check if we've searched for this term before
if(query in cache){
results = cache[query];
//Case insensitive search for our people array
var results = $.grep(people, function(item){
return, "i")) != -1;
//Add results to cache
cache[query] = results;
//First search
if(drew == false){
//Create list for results
$("#search").after('<ul id="res"></ul>');
//Prevent redrawing/binding of list
drew = true;
//Bind click event to list elements in results
$("#res").on("click", "li", function(){
//Clear old results
//Add results to the list
for(term in results){
$("#res").append("<li>" + results[term] + "</li>");
//Handle backspace/delete so results don't remain
else if(drew){
<input id="search" type="text">
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment