A Simple JQuery Autocomplete Search Tutorial

In this Tutorial I will explain How to Create a Simple Autocomplete search functionality using jQuery.

Look at the jQuery AutoComplete Demo

A quick Google search will return so many jQuery autocomplete libraries and plugins and in that jQuery UI Autocomplete library is popular and widely used library.

But in this tutorial I am using Twitter Typeahead.js plugin :  An open source autocomplete JavaScript library by Twitter.

It comes with so many features like

  • Display suggestions to user as they types.
  • Shows suggestions like Google Autocomplete Search
  • Works with hard coded Data and as well as remote data
  • Suggestions from multiple Data sets.
  • Supports customized templates for suggestions.

First we will start with basic implementation of jQuery autocomplete using Twitter Typeahead.js which uses single data set.

Look at the sample HTML Code

<input class="countries" type="text" placeholder="Countries">

 

I created simple Textbox with class “Countries” and now we have to assign data to this Textbox.

Look at the below code.

$('input.counties').typeahead({
      name: 'countries',
      local: ["Unites States", "Mexico", "Canada", "Cuba", "Guatemala"]
});

 

‘local’ attribute is used for hard coded json data.

Twitter Typeahead js

Twitter Typeahead js

 

How this Twitter Typeahead.js will work:

Whenever you add data to the text box using typeahead object it will generate some dynamic html code for displaying suggestion lists (you can see this code by inspecting the textbox element).

Twitter Typeahead Working

Twitter Typeahead Working

 

And in the demo I added some styles like text box on focus blue color and suggestion hover blue color.

If you want to add your own styles.Add styles to following classes “tt-query, tt-hint, tt-dropdown-menu, tt-suggestion” which are generated by Twitter Typeahead.js library.

Multiple Data Sets Suggestion Using Twitter Typeahead.js :

Now I will show you how to implement multiple data set suggestions.

We have to search for city names from different countries. For instance US and Canada,Sample Json Data

//United States
['New York', 'Los Angeles', 'Chicago', 'Houston', 'Philadelphia']

//Canada
["Toronto", "Montreal", "Calgary", "Ottawa", "Edmonton", "Peterborough"]

 

In the above example I used hard coded json data (client side). In this example we retrieve json data from server side.

I saved above json data into two files US.json and Canada.json.

$('input.countries-cities').typeahead([
                {
                    name: 'Canada',
                    prefetch: 'https://www.arungudelli.com/Tools/HTML5/jQueryAutoComplete/Canada.json',
                    header: '<h3>Canada</h3>'

                },
                {
                    name: 'United States',
                    prefetch: 'https://www.arungudelli.com/Tools/HTML5/jQueryAutoComplete/US.json',
                    header: '<h3>United States</h3>'

                }

            ]);

 

We have to use ‘prefetch’ attribute to retrieve json data from an URL.

And I used ‘header’ attribute to display country Name as a header for two Data sets.

Twitter Typeahead.js library provides one more attribute ‘footer’ to display footer name. I am not using ‘footer’ attribute. You can try it.

Here is the demo.

twitter typeahead Js

twitter typeahead Js

Actually this ‘prefetch’ will grab the data from json on pageload and then stores it in browser’s Local Storage. You can see the json data in local Storage.

Twitter Typeahead Prefetch

Twitter Typeahead Prefetch

 

Now I will explain how to customize suggestions using Twitter Typeahead.js

Twitter Typeahead.js Customized templates for suggestions:

I liked this feature very much we can easily customize suggestion list based upon our requirements.

Take an example of  a blog we will be having different categories, for instance  HTML5,JavaScript,CSS3. Now we are searching for a particular post by Post name or title.

In search suggestion box we have to show Title,Category and Small Description with some styles.Like Post Name in bold font,below that small description and Category in Italic font and right side of suggestion box.

Twitter Typeahead.js library provides ‘template’ attribute to define our own styles.And to use this templates we have to provide template ‘engine’. Typeahead.js comes with one default engine called “Hogan”.

Sample Json data which contains keys like tag,name and description

[
{ "tag": "HTML5", "name": "HTML5 LocalStorage API", "description": "HTML5 LocalStorage API,Client Side Storage" },
        { "tag": "HTML5", "name": "HTML5 GeoLocations API", "description": "HTML5 GeoLocations API,Used to Find Location" },
        { "tag": "JavaScript", "name": "JavaScript Tips And Tricks", "description": "Some Useful Javascript tips and tricks" },
        { "tag": "JavaScript", "name": "JavaScript Tutorials", "description": "JavaScript Tutorials" },
        { "tag": "CSS3", "name": "CSS3 Animations", "description": "CSS3 Animations" },
        { "tag": "CSS3", "name": "CSS3 Tutorial", "description": "CSS3 Tutorial" }
]

 

Now we have to pass this json data along with template

$('.WordpressPosts').typeahead({
    name: 'Wordpress',
    valueKey: 'name',
    prefetch: 'https://www.arungudelli.com/Tools/HTML5/jQueryAutoComplete/Tags.json',
    template: [
    '<p class="repo-tag">{{tag}}</p>',
    '<p class="repo-name">{{name}}</p>',
    '<p class="repo-description">{{description}}</p>'
  ].join(''),
     engine: Hogan
});

 

‘valueKey’ attriutes defines the search criteria. For this example we have to search by post name. so I given ‘valueKey’ as “name”.

I defined a custom template for suggestion box which displays tag,name and description. We have to use {{}} to display Json Data. and I used Hogan template engine.

And HTML Code

<div class="CustomTemplate">
                <h4>Uses Custom Template For rendering Suggesstions</h4>
                <input class="WordpressPosts typeahead" type="text" placeholder="My WordPress Posts" />
            </div>

 

We have to add Hogan.js library in header part along with jQuery,typeahead JavaScript libraries.

Now we have to apply style to this template.

.CustomTemplate .repo-tag {
  float: right;
  font-style: italic;
}

.CustomTemplate .repo-name {
  font-weight: bold;
}

.CustomTemplate .repo-description {
  font-size: 14px;
}

 

Here is the Final jQuery AutoComplete Demo

But the problem with the prefetch attribute is it will save the entire Json data into the browser’s Local Storage which is not the feasible solution for sites like Twitter and Google. i.e., you have to return results from the server as-you-type.

Twitter Typeahead.js provides ‘remote’ attribute in which we can pass a search string as query parameter to server to return results from Database as-we-type.

In my next post I will explain about this ‘remote’ attribute.You may use PHP or Asp .net to retrieve data from server. I am familiar with Asp .net MVC. Go through jQuery Autocomplete using Asp Net MVC article to learn how retrieve data from server using Twitter Typeahead.js remote attribute.

Download the source Code for jQuery Autocomplete Tutorial

I hope you have enjoyed this article.If so share this post with your friends and also join our mailing list.