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, 7 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, 3 weeks 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 - 4 months, 3 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 - 4 months, 1 week 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 - 3 weeks, 6 days 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 - 2 months, 2 weeks ago

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

    reply

  • linkolned - 2 months, 1 week ago

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

    reply

  • business news - 1 month, 1 week 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 - 1 month, 1 week 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 - 1 month, 1 week 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 month 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 month 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 month 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 month ago

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

    reply

  • heavyrentals - 3 weeks, 5 days ago

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

    reply

  • visit website - 6 days, 18 hours ago

    I just wanna say thanks for the writer and wish you all the best for coming!

    reply

  • Ottawa SEO - 15 hours ago

    I know your expertise on this. I must say we should have an online discussion on this. Writing only comments will close the discussion straight away! And will restrict the benefits from this information.

    reply

  • antilla vector-czarter - 1 month 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

  • acupuncture nyc - 1 week, 6 days ago

    I am genuinely thankful to the holder of this web page who has shared this wonderful paragraph at at this place.

    reply

  • best vitamin c serum for face - 1 week, 5 days ago

    Great photos are you using the 60 mm? Any tips for getting shots like this amazing body of work in photography.

    reply

  • code triche clash of clans - 1 week, 3 days ago

    Ceci est un grand article, Merci de me donner cette information. Gardez annonce

    reply

  • click here - 1 month 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 - 3 weeks, 6 days 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 - 3 weeks, 6 days ago

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

    reply

  • Pregnancy Miracle Guide - 1 week, 6 days ago

    We are really grateful for your blog post. You have done a great job. I will definitely dig it and personally recommend to my friends

    reply

  • vit c serum - 1 week, 4 days ago

    Nice information, valuable and excellent design, as share good stuff with good ideas and concepts, lots of great information and inspiration, both of which I need, thanks to offer such a helpful information here.

    reply

  • phen375 2015 - 1 week, 1 day ago

    AWesome blog post i really like the quality of content, it was exactly what i was looking for thanks for writing, keep it up. Good Luck

    reply

  • This Site - 3 days, 15 hours ago

    I think this is an informative post and it is very useful and knowledgeable. therefore, I would like to thank you for the efforts you have made in writing this article

    reply

  • www.luckies.co.uk - 1 day, 5 hours ago

    Excellent .. Amazing .. I’ll bookmark your blog and take the feeds also…I’m happy to find so many useful info here in the post, we need work out more techniques in this regard, thanks for sharing.

    reply

  • joshua pellicer - 1 week, 3 days ago

    I should say only that its awesome! The blog is informational and always produce amazing things.

    reply

  • Amazing Selling Machine 5 Bonus - 1 month 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 month 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

  • Free Minecraft Account 2015 - 1 week, 6 days ago

    This is also a very good post which I really enjoyed reading. It is not every day that I have the possibility to see something like this

    reply

  • vitamin c for skin - 1 week, 3 days ago

    I don't know what to say except that I have enjoyed reading. Nice blog.

    reply

  • VIP Care Pavilion - 1 week ago

    Good post. I learn some thing tougher on distinct blogs everyday. Most commonly it really is stimulating to learn to read content material from other writers and exercise a specific thing there.

    reply

  • man and van - 2 days, 17 hours ago

    Do you mind updating your blog post with additional insight? It should be really useful for all of us.

    reply

  • best seo company  - 1 month 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 month ago

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

    reply

  • Hidden spy cameras - 1 month 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

  • No credit check loans 2015 - 1 day, 18 hours ago

    My friend mentioned to me your blog, so I thought I’d read it for myself. Very interesting insights, will be back for more!

    reply

  • mens slim suit - 1 month 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 month 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 - 3 weeks, 5 days ago

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

    reply

  • foto tapety - 3 weeks, 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

  • The Waxing Hub - 3 weeks, 3 days ago

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

    reply

  • GB Vehicle Hire - 3 weeks, 3 days 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 - 3 weeks, 3 days 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 - 3 weeks, 3 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 - 3 weeks, 2 days 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

  • Psychic Reading - 2 weeks, 6 days ago

    Your music is amazing. You have some very talented artists. I wish you the best of success.

    reply

  • loft conversions - 2 weeks, 6 days ago

    I love this blog!! The flash up the top is awesome!!

    reply

  • agenzie immobiliari a Monaco - 2 weeks, 2 days ago

    I know your expertise on this. I must say we should have an online discussion on this. Writing only comments will close the discussion straight away! And will restrict the benefits from this information.

    reply

  • High School Diploma Online - 1 week, 4 days ago

    Wonderful post i have got here keep it up

    reply

  • manabadi eamcet results 2015 - 1 week ago

    I know your expertise on this. I must say we should have an online discussion on this. Writing only comments will close the discussion straight away! And will restrict the benefits from this information.

    reply

  • manabadi eamcet results 2015 - 1 week ago

    I love this blog!! The flash up the top is awesome!!

    reply

  • starofservice.co.ve - 1 week, 3 days ago

    Such a very useful article. Very interesting to read this article.I would like to thank you for the efforts you had made for writing this awesome article. <a href="http://starofservice.co.ve">starofservice.co.ve</a>

    reply

  • packers and movers - 1 week, 1 day ago

    http://1support.co.in/packers-and-movers-hyderabad/

    reply

  • packers and movers - 1 week, 1 day ago

    http://1support.co.in/packers-and-movers-bangalore/

    reply

  • packers and movers - 1 week, 1 day ago

    http://1support.co.in/packers-and-movers-chennai/

    reply

  • packers and movers - 1 week, 1 day ago

    http://1support.co.in/packers-and-movers-delhi/

    reply

  • packers and movers - 1 week, 1 day ago

    http://1support.co.in/packers-and-movers-gurgaon/

    reply

  • packers and movers - 1 week, 1 day ago

    http://1support.co.in/packers-and-movers-noida/

    reply

  • packers and movers - 1 week, 1 day ago

    http://1support.co.in/packers-and-movers-pune/

    reply

  • packers and movers - 1 week, 1 day ago

    http://1support.co.in/packers-and-movers-mumbai/

    reply

  • packers and movers - 1 week, 1 day ago

    http://1support.co.in/packers-and-movers-ghaziabad/

    reply

  • packers and movers - 1 week, 1 day ago

    http://1support.co.in/packers-and-movers-kolkata/

    reply

  • packers and movers - 1 week, 1 day ago

    http://1support.co.in/packers-and-movers-faridabad/

    reply

  • packers and movers - 1 week, 1 day ago

    http://1support.co.in/packers-and-movers-lucknow/

    reply

  • packers and movers - 1 week, 1 day ago

    http://1support.co.in/packers-and-movers-indore/

    reply

  • High School Diploma Online - 1 week ago

    Good post.

    reply

  • st lucia 4x4 car hire - 6 days, 13 hours ago

    Thanks for posting this info. I just want to let you know that I just check out your site and I find it very interesting and informative. I can't wait to read lots of your posts.

    reply

  • Sewing alterations Maida Vale - 6 days, 11 hours ago

    Very useful post. This is my first time i visit here. I found so many interesting stuff in your blog especially its discussion. Really its great article. Keep it up.

    reply

  • http://www.tactus.lt - 6 days, 9 hours ago

    Excellent website you have here, so much cool information!..

    reply

  • loft conversions - 1 day, 11 hours ago

    but I'd like to say that this article really forced me to do so. Really nice post!

    reply

  • backlinks - 6 days, 3 hours ago

    I just couldn't leave your website before telling you that I truly enjoyed the top quality info you present to your visitors? Will be back again frequently to check up on new posts.

    reply

  • gabinet okulistyczny optykdutkiewicz.pl - 5 days, 15 hours ago

    Interesting and amazing how your post is! It Is Useful and helpful for me That I like it very much, and I am looking forward to Hearing from your next..

    reply

  • DPM - 15 hours ago

    Excellent article. Very interesting to read. I really love to read such a nice article. Thanks! keep rocking.

    reply

  • chocolate cupcake recipe - 5 days, 14 hours ago

    am are really grateful for your blog post. You have done a great job.It's nice to see that some people still understand how to write a quality post!please share some more articles like this.thanks

    reply

  • Sam - 4 days, 19 hours ago

    Thank you for sharing this post here!!!! <a href="http://www.myntra.com/">Click</a>

    reply

  • Click - 4 days, 19 hours ago

    Thank you for sharing this post here!!!!

    reply

  • loft conversions london - 3 days, 11 hours ago

    Very good points you wrote here..Great stuff...I think you've made some truly interesting points.Keep up the good work.

    reply

  • loftplan liquidation - 2 days, 14 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

  • military auto insurance - 1 day, 15 hours 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

  • commercial insurance company - 1 day, 13 hours ago

    I really appreciate this wonderful post that you have provided for us. I assure this would be beneficial for most of the people.

    reply

  • Hindi Sms - 1 day, 11 hours ago

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

    reply

  • http://rebelmouse.com/ - 11 hours ago

    These are some great tools that i definitely use for SEO work. This is a great list to use in the future..

    reply

  • http://rebelmouse.com - 10 hours 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