Autocomplete Input Box Using "Typeahead" jQuery Plugin

Introduction

In this blog, we will see how to implement an autocomplete input box using "Typeahead" jQuery plugin.

Typeahead is an open source jQuery based autocomplete plugin developed by Twitter. You can find more details and examples of the plugin here.

Now, we will see how to integrate it in our HTML input box.

For example, we can consider an input box for searching an employee's name.

  1. <div style="width: 280px;"> Employee name :  
  2.     <input id="inputbox" class="typeahead" type="text" placeholder="Enter Name" style="padding: 5px 10px;   
  3. margin-top: 10px; border: 1px solid #c3c3c3; width: 260px; border-radius: 5px;"> </div>  
Now, we should reference the below JS / CSS files in our page head for this Typeahead autocomplete plugin to work.
  1. <link href="typeahead.css" rel="stylesheet" type="text/css" />  
  2. <script src="jquery.min.1.11.1.js" type="text/javascript"></script>  
  3. <script src="typeahead.jquery.js" type="text/javascript"></script>  
Now, initialize the input box with Typeahead.
  1. <script type="text/javascript">  
  2.     $(function() {  
  3.         $('#inputbox').typeahead({  
  4.             minLength: 3,  
  5.             highlight: true  
  6.         }, {  
  7.             name: 'autofill',  
  8.             source: substringMatcher(getdata()),  
  9.             limit: 10  
  10.         });  
  11.     });  
  12. </script>  
Explanation of the options passed in the above script 
  • min-length
    It is the minimum number of characters to be entered in input box for the search to work.

  • highlight
    Whether the searched text should be highlighted in results or not.

  • limit
    The maximum number of results to be shown in search result box.

  • source
    This is the most important option in typeahead.jquery.js. We have to set the source for searching during initialization of input box with Typeahead.

In the above example, we have used two functions as value for source.

The first one is getdata().

  1. <script type="text/javascript">  
  2.     function getdata() {  
  3.         var datas;  
  4.         $.ajax({  
  5.             url: 'jsondata.aspx',  
  6.             async: false  
  7.         }).done(function(data) {  
  8.             datas = data;  
  9.         });  
  10.         return datas;  
  11.     }  
  12. </script>  
This function contains an AJAX method which calls a page and fetches complete employees names in JSON format and returns that data.

The AJAX page contains the below code on page load.
  1. protected void Page_Load(object sender, EventArgs e) {  
  2.     Response.AddHeader("content-type""application/json");  
  3.     Response.Write("[\"Rajeev\",\"Sanjay\",\"Samuel\",\"Samson\",\"Ameer\",\"Anand\",\"Sania\",\"Sanal\",\"Rekha\",\"Sanju\",\"Sanuja\"]");  
  4. }  
Now, this data is passed to the method substringMatcher();
  1. <script type="text/javascript">  
  2.     var substringMatcher = function(strs) {  
  3.         return function findMatches(q, cb) {  
  4.             var matches, substringRegex;  
  5.             // An array that will be populated with substring matches   
  6.             matches = [];  
  7.             // regex used to determine if a string contains the substring `q`   
  8.             substrRegex = new RegExp(q, 'i');  
  9.             // Iterate through the pool of strings and for any string that   
  10.             // contains the substring `q`, add it to the `matches` array   
  11.             $.each(strs, function(i, str) {  
  12.                 if (substrRegex.test(str)) {  
  13.                     matches.push(str);  
  14.                 }  
  15.             });  
  16.             cb(matches);  
  17.         };  
  18.     };  
  19. </script>  
This is the most important method in Typeahead, that searches for the entered string in complete data array and returns the matching results.

Now, we can run our page.

typeahead

Now, enter some characters of employee name. We can see the results in the result box, as below.

typeahead

We can edit the typeahead.css file for changing the look and feel of the search box accordingly.

Additional options

We can call any script while selecting one result from the result box, using the below script.
  1. <script type="text/javascript">  
  2.     $(function() {  
  3.         $('#inputbox').bind('typeahead:selected'function(obj, data) {  
  4.             //Here 'data' will give the selected item   
  5.         });  
  6.     });  
  7. </script>  
In the above script, the variable "data" will give us the selected item.

Summary

In this article, we have learned how to implement an autocomplete input box in our website using the open source Typeahead jQuery plugin.

Hope it will be helpful!
Ebook Download
View all
Learn
View all