Create Your Own jQuery Autocomplete Function (Posted on January 19th, 2013)

It's always nice when text or code autocompletes for you. Why not give your users the same happiness on your site?

I'm aware that there are several autocomplete libraries out there. I've personally used jQuery UI's autocomplete which is really nice and simple. However, I feel that creating an autocomplete widget is simple enough to prevent the need of including another large javascript library. The final compressed javascript for this project only adds 608 bytes and could likely be modified to be less.

Let's Search

Right now we're just going to setup the search functionality in our javascript. No results will be displayed to the end user, however, you can alert the "results" variable to verify that things are working as intended.

$(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;
            }
        }
    });
});

We first check our cache to see if we've already searched for the term before. If we haven't then we use jQuery's grep to compile our results. The function we search with does a case insensitive search across each item in the people list for the value in our text box. Once we've got our results we add them to the cache for later use. The "drew" variable will be used in the next step to check if we need to redraw our results list or not.

Draw The Results!

Now we're going to go ahead and create a list below our search input so that we can view the results that search function returns. The new code starts on line 25

$(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 with less than 3 characters
        else if(drew){
            $("#res").empty();
        }
    });
});

In order to place our search results we add an empty list right below our search input. We only want to do this once which is why we use the "drew" variable for a simple way to keep track of the list has been added or not. We also want to bind a click event to the items in our list so that a user can select their choice and have the input box automatically filled. The final step is to actually add the items to the list. We cycle through the results array and append each item to the "#res" list.

Here's an example of how it could look with some styling:

jQuery Autocomplete example

You can download a gist of this styled version to play around with on your own if you'd like. For a quick fun challenge try moving the search function to a backend script such as PHP and querying it using AJAX.

As always if you have any feedback or questions feel free to drop them in the comments below or contact me privately on my contact page.

Tags: jQuery