Create jQuery Autocomplete

jQuery Autocomplete enables users to quickly find and select from a pre-populated list of values as they type, leverage, search and filter. Autocomplete can be done with both client side data and server side. Client side means we fetch data only once then the filter will be applied on that data. Server side means as and when user types it goes to server and fetches relevant data.

Client Side Autocomplete:

Javascript:

  1. $(document).ready(function()   
  2. {  
  3.     //simple javascript string array   
  4.     var availableKeywords = [  
  5.         "ActionScript",  
  6.         "BASIC",  
  7.         "C",  
  8.         "C++",  
  9.         "Erlang",  
  10.         "Fortran",  
  11.         "Groovy",  
  12.         "Haskell",  
  13.         "Java",  
  14.         "JavaScript",  
  15.         "Python",  
  16.         "Ruby",  
  17.         "Scala",  
  18.         "Scheme"];  
  19.   
  20.     //Initialize autocomplete with the above array   
  21.     $("#keywords").autocomplete({  
  22.         source: availableKeywords  
  23.     });  
  24.   
  25. });
Html:
  1. <div class="ui-widget">   
  2. <label for="keywords">Keywords: </label>   
  3. <input id="keywords">   
  4. </div>   
The above example is based on client side data. Here the data is at client side in the form of an array, but many times we may need data from the server dynamically. So here I will explain how to do that. When we deal with server side, we should first define a url which serves the request from the client. Server should return data in JSON format.

Autocomplete with Remote Data:

Javascript:
  1. $("#cities").autocomplete({  
  2.   
  3.     source: "search.php"//Url which serves the request  
  4.   
  5.     minLength: 2, //minimum characters needed to request data from server  
  6.   
  7.     select: function(event, ui)   
  8.     {  
  9.   
  10.         //do something on selection   
  11.   
  12.     }  
  13.   
  14. });
Html:
  1. <div class="ui-widget">   
  2. <label for="cities">Cities: </label>   
  3. <input id="cities">   
  4. </div>
Note: jQuery autocomplete requires jquery-ui.js external javascript file.
X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now