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

Comments:

  • Explicat - 1 year, 6 months ago

    Thanks for sharing! I always prefer small self-written solutions to big plugins and your code pretty much does what I was looking for.

    reply

  • Ardoped - 10 months ago

    This is -exactly- what I was looking for. As a beginner jQuery programmer, this explains so much of the logic. Thank you VERY much!

    reply

  • AnhTuan - 3 months, 4 weeks ago

    Great and really helpful tutorial! However I can't do the AJAX part. I tried to use xmlhttprequest and send function but I don't know how to move the search function into a php file. Could you provide some help?

    reply

  • Max Burstein - 3 months, 2 weeks ago

    Try creating a PHP file that sends back JSON data. Then when you receive data you can just call JSON.parse(response) and iterate over it that way.

    reply

  • Targeting Inspector 2.0 - 5 days, 1 hour ago

    Interesting topic for a blog. I have been searching the Internet for fun and came upon your website. Fabulous post. Thanks a ton for sharing your knowledge! It is great to see that some people still put in an effort into managing their websites. I'll be sure to check back again real soon.

    reply

  • Danilinved - 1 month, 3 weeks ago

    Begin saving money when you <a href="http://buyedtabletsonline24-7.com/">purchase viagra</a> from leading pharmacies

    reply

  • linkolned - 1 month, 3 weeks ago

    Save by searching for <a href="http://www.sikhdocs.org/">cialis</a> you can save dollars.

    reply

  • business news - 2 weeks, 5 days ago

    Thanks for taking the time to discuss that, I feel strongly about this and so really like getting to know more on this kind of field. Do you mind updating your blog post with additional insight? It should be really useful for all of us.

    reply

  • boom beach hack - 2 weeks, 3 days ago

    I high appreciate this post. It’s hard to find the good from the bad sometimes, but I think you’ve nailed it! would you mind updating your blog with more information?

    reply

  • subway surfers cheats - 2 weeks, 2 days ago

    Your article has piqued a lot of positive interest. I can see why since you have done such a good job of making it interesting.

    reply

  • http://lovecabtours.com/ - 1 week, 6 days ago

    Yes i am totally agreed with this article and i just want say that this article is very nice and very informative article.I will make sure to be reading your blog more. You made a good point but I can't help but wonder, what about the other side? !!!!!!THANKS!!!!!!

    reply

  • more books - 1 week, 6 days ago

    Wonderful illustrated information. I thank you about that. No doubt it will be very useful for my future projects. Would like to see some other posts on the same subject!

    reply

  • state farm auto insurance rate quotes - 1 week, 6 days ago

    This is very educational content and written well for a change. It's nice to see that some people still understand how to write a quality post!

    reply

  • amazing selling machine - 1 week, 6 days ago

    Awesome and interesting article. Great things you've always shared with us. Thanks. Just continue composing this kind of post.

    reply

  • heavyrentals - 4 days, 5 hours ago

    The post is written in very a good manner and it contains many useful information for me.

    reply

  • antilla vector-czarter - 1 week, 5 days ago

    Pretty good post. I just stumbled upon your blog and wanted to say that I have really enjoyed reading your blog posts. Any way I'll be subscribing to your feed and I hope you post again soon. Big thanks for the useful info.

    reply

  • click here - 1 week, 5 days ago

    This is a great inspiring article.I am pretty much pleased with your good work.You put really very helpful information...

    reply

  • shadow fight 2 hack - 4 days, 22 hours ago

    I'm glad I found this web site, I couldn't find any knowledge on this matter prior to.Also operate a site and if you are ever interested in doing some visitor writing for me if possible feel free to let me know, im always look for people to check out my web site.

    reply

  • summoners war hack - 4 days, 22 hours ago

    The post is written in very a good manner and it contains many useful information for me.

    reply

  • Amazing Selling Machine 5 Bonus - 1 week, 4 days ago

    Its a great pleasure reading your post.Its full of information I am looking for and I love to post a comment that "The content of your post is awesome" Great work.

    reply

  • bring the fresh 2015 - 1 week, 4 days ago

    This is such a great resource that you are providing and you give it away for free. I love seeing websites that understand the value of providing a quality resource for free. It is the old what goes around comes around routine.

    reply

  • best seo company  - 1 week, 4 days ago

    Thanks for sharing the post.. parents are worlds best person in each lives of individual..they need or must succeed to sustain needs of the family.

    reply

  • stampa grafica viterbo - 1 week, 3 days ago

    Your website is really cool and this is a great inspiring article.

    reply

  • Hidden spy cameras - 1 week, 2 days ago

    I havent any word to appreciate this post.....Really i am impressed from this post....the person who create this post it was a great human..

    reply

  • mens slim suit - 1 week, 2 days ago

    This is a great inspiring article.I am pretty much pleased with your good work.You put really very helpful information. Keep it up. Keep blogging. Looking to reading your next post.

    reply

  • indoor antennas - 1 week, 2 days ago

    Nice to be visiting your blog once more, it has been months for me. Well this article that ive been waited for therefore long. i want this article to finish my assignment within the faculty, and it has same topic together with your article. Thanks, nice share.

    reply

  • Einblick - 4 days, 4 hours ago

    Great post, and great website. Thanks for the information!

    reply

  • foto tapety - 4 days, 1 hour ago

    Pretty good post. I just stumbled upon your blog and wanted to say that I have really enjoyed reading your blog posts. Any way I'll be subscribing to your feed and I hope you post again soon. Big thanks for the useful info.

    reply

  • The Waxing Hub - 2 days, 6 hours ago

    Absolutely fantastic posting! Lots of useful information and inspiration, both of which we all need!Relay appreciate your work.

    reply

  • GB Vehicle Hire - 2 days, 4 hours ago

    You know your projects stand out of the herd. There is something special about them. It seems to me all of them are really brilliant!

    reply

  • Aquatic Store - 2 days, 3 hours ago

    I have read your blog it is very helpful for me. I want to say thanks to you. I have bookmark your site for future updates.

    reply

  • http://www.infinitemediadesign.co.uk - 2 days ago

    Positive site, where did u come up with the information on this posting? I'm pleased I discovered it though, ill be checking back soon to find out what additional posts you include.

    reply

  • superior papers - 20 hours ago

    When virtue and modesty enlighten her charms, the lustre of a beautiful woman is brighter than the stars of heaven, and the influence of her power it is in vain to resist.

    reply