$(document).ready(function() {
var people = ['Peter Bishop','Peterim Bishop', 'Petercon Bishop', 'Nicholas Brody', 'Gregory House', 'Hank Lawson', 'Tyrion Lannister', 'Nucky Thompson'];
var cache = {};
var drew = false;
var srchBox = $("#srchme");
var resBox = $("#res");
srchBox.wrap( "<ul class='ausuggest'><li></li></ul>" );
var searchBoxLi = srchBox.parent();
srchBox.on("keyup", function(event) {
var query = srchBox.val()
if (srchBox.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) {
//#srchme list for results
srchBox.after('<ul id="res"></ul>');
//Prevent redrawing/binding of list
drew = true;
//Bind click event to list elements in results
resBox.on("click", "li", function() {
var searchVal = $(this).text();
var selValLi = $( "<li class='sel'>"+$(this).text()+"</li>" );
selValLi.insertBefore(searchBoxLi)
srchBox.val("");
resBox.empty();
});
}
//Clear old results
else {
resBox.empty();
}
//Add results to the list
for (term in results) {
resBox.append("<li>" + results[term] + "</li>");
}
}
//Handle backspace/delete so results don't remain with less than 3 characters
else if (drew) {
resBox.empty();
}
});
});
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.