Skip to content

Instantly share code, notes, and snippets.

@mburst
Created January 19, 2013 20:51
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save mburst/4575043 to your computer and use it in GitHub Desktop.
Save mburst/4575043 to your computer and use it in GitHub Desktop.
jQuery Autocomplete
<!DOCTYPE html>
<html>
<head>
<title>jQuery Autocomplete</title>
<style>
#res {
margin: 0px;
padding-left: 0px;
width: 150px;
}
#res li {
list-style-type: none;
}
#res li:hover {
background: #110D3B;
color: #FFF;
cursor: pointer;
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
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];
}
else{
//Case insensitive search for our people array
var results = $.grep(people, function(item){
return item.search(RegExp(query, "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(){
$("#search").val($(this).text());
$("#res").empty();
});
}
//Clear old results
else{
$("#res").empty();
}
//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){
$("#res").empty();
}
});
});
</script>
</head>
<body>
<input id="search" type="text">
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment