Sunday, January 31, 2016

ASP.NET MVC web application : Autocomplete using JQuery Autocomplete Plugin


Introduction

In this article, we will study the autocomplete plugin of jquery-ui, it provides suggestions while tapping text into the search bar.
Most web sites such us Google, Yahoo, etc. adopt this technique of searching assistance.
In this article, we will:
  • Learn about using Autocomplete plugin
  • Know how to load list of suggestions from internal and external data

Background

This article may be useful for intermediate developers who have some basics in HTML, Ajax, JQuery, JavaScript, C# and ASP.NET.

I) About the Autocomplete Plugin

About

This widget is used to generate a suggestion list for user when writing text into an input text. The result of list will be sorted depending on word composed.
If you register word beginning with AB, we will have a list of suggestions sorted by relevance (according to the place of word: word-beginning, middle or at the end).
The famous search engine such as Google has been using this technology for a long time, that helps users to find which query goes with the thing to look.







The word Hap was interpreted by Google, which returned four suggestions.
It is possible to navigate easily among the proposals through the keys of your keyboard , , do a choice by clicking on and cancel the searching by .

Option and Events

Autocomplete as plugin has multiple options and arguments to be defined.

a) minLength

This option specifies the minimum length required for the string typed by user,
As default, this argument has 1, means that the proposal list appears at the bottom of the text when user writes one character. When changing the parameter, you reduce the suggestion list.
 $('#search').autocomplete({  
   source : [...], //data source  
   minLength : 3 //the suggestion list appears after tapping 3 characters   
 });  

b) Source

This option requires a table that contains a list of suggestions it considered as a database from which the search is performed.
The source data can seek on list generated locally or from outside (url).
 var list = [  
   "Test",  
   "Test 2",  
   "Test 3"  
 ];  
 $('#search').autocomplete({  
   source : list  
 });  
 
In the step of initialization of list, we can better present it by adding other option for each row:
  • value: the value to be entered in the text field when selected
  • label: the title of suggestion
  • desc: specify a description for the suggestion
  • icon: show icon for suggestion
    var list = [
        { value : 'Test'  , label : 'Label Test'},
        { value : 'Test 1', label : 'Label Test 1'},
        { value : 'Test 2', label : 'Label Test 2'}
    ];

c) Position

Define the position of list of suggestion, by default, it appears on the bottom of the text.
We can change the position of list, by the following parameters:
  • my: define the position of list around the text
  • at: define the start position of list inside the text
   $('#search').autocomplete({  
     source : [...],  
     position : {  
       my : 'bottom',  
       at : 'top'  
     } //list is positioned above and outside of text field.  
   });  

d) Select

Detect an event of selection item action on list of suggestion.
   $('#search').autocomplete({  
     source : [...],  
     select : function(event, ui){  
       alert( ui.item.value ); // start an alert which contains the value of proposal  
     }  
   });  
ui.item.value: value can be replaced by an option of a row list discussed above.

e) Open and Close

Allow programmer to manage the event of opening and closing of suggestion list.

II) Example of Use

In this section, we will see two modes of loading data into Auto-Complete plugin.
First, you must import Jquery-ui libraries to use AutoComplete plugin.
 <!-- jQuery -->  
 <script src="/Content/js/jquery.min.js"></script>  
 <!-- jQuery ui CSS-->  
 <link href="/Content/css/jquery-ui.min.css" rel="stylesheet" type="text/css">  
 <!-- jQuery ui JS-->  
 <script src="/Content/js/jquery-ui.min.js"></script>  
 

1) Loading Data from Local Source Data

In this example, the data will be loaded staticly from a local list, data loaded can be a list or array of data.

a) Code JavaScript

   $(document).on('focus', '#idLocalNames', function () {  
     var list = [  
       "Test",  
       "Test 2",  
       "Test 4",  
       "Example 1",  
       "Example 2"  
         ];  
     $(this).autocomplete({  
       //source take a list of data  
       source: list,  
       minLength: 1//min = 2 characters  
     });  
   });  

b) Code Html

   <input type="text" id="idLocalNames" class="form-control" onfocus="this.value = '';"  
   placeholder="Write a character">  

To use this example, you can write 'T' and you will get a list of suggestions composed by words that start with the character 'T'.

2) Loading Data from External Source Data

In this example, data loaded staticly by sending request to an external source of data (for example, a service that fetches data from the Server database), which data can be loaded on demand and depends on text written.

a) Code JavaScript

   $(document).on('focus', '#idExternalNames', function () {  
     $(this).autocomplete({  
       //source have a url of a service  
       source: '@Url.Action("AutoCompleteExternalData")',  
       minLength: 1//min = 2 caract&egrave;res  
     });  
   });  

b) Code C#

   public class HomeController : Controller  
   {  
     public ActionResult Index()  
     {  
       return View();  
     }  
     public ActionResult AutoCompleteExternalData(string term /*our key word*/)  
     {  
       //items is the source data and can be replaced by a request to a DataBase  
       string[] items = {"Test", "Test 1", "Test 2",  
       "Example 1", "Example 2", "Example 3"};  
       //we did a fetch of term from items  
       var filteredItems = items.Where(  
      item => item.IndexOf(term, StringComparison.InvariantCultureIgnoreCase) >= 0);  
       //we return a json data  
       return Json(filteredItems, JsonRequestBehavior.AllowGet);  
     }  
  }  

c) Code Html

<input type="text" id="idExternalNames" class="form-control" onfocus="this.value = '';"
  placeholder="Write a character">
 
To use this example, you can write 'Example' and you will get a list of suggestions composed by word that start with 'Example'.

3) Example in How to Use Label and Value of Source Option

a) Code JavaScript

  $(document).on('focus', '#idLocalNamesExample2', function () {  
   var list = [  
      { value : '0', label : 'Test'},  
      { value : '1', label : 'Test 1'},  
      { value : '2', label : 'Test 2'}  
   ];  
   $(this).autocomplete({  
     //source take a list of data  
     source: list,  
     minLength: 1//min = 2 characters  
   });  
 });  
 $(document).on('focus', '#idExternalNamesExample2', function () {  
   $(this).autocomplete({  
     //source have a url of a service  
     source: '@Url.Action("AutoCompleteExternalDataExample2")',  
     minLength: 1//min = 2 characters  
   });  
 });  

b) Code C#

 public ActionResult AutoCompleteExternalDataExample2(string term /*our key word*/)  
   {  
     //items is the source data and can be replaced by a request to a DataBase  
     string[] items = {"Test", "Test 1", "Test 2",  
     "Example 1", "Example 2", "Example 3"};  
     //initialize the list of AutoList object  
     List<AutoList> filteredItems = new List<AutoList>();  
     int cp = 0;  
     foreach (var elem in items)  
     {  
       if (elem.IndexOf(term, StringComparison.InvariantCultureIgnoreCase) >= 0)  
       {  
         cp++;  
         //buil our result list  
         AutoList autoList = new AutoList(""+cp, elem);  
         filteredItems.Add(autoList);  
       }  
     }  
     return Json(filteredItems, JsonRequestBehavior.AllowGet);  
   }  

c) Class AutoList

 public class AutoList  
 {  
   public string label;  
   public string value;  
   public AutoList(string value, string label)  
   {  
     this.value = value;  
     this.label = label;  
   }  
 }  

d) Code Html

  <div class="row">  
   <div class="col-lg-5">  
     <div class="panel panel-default">  
       <div class="panel-heading">  
         Using Label & value attribute (local Source Example):  
       </div>  
       <div class="panel-body">  
         <div class="input-group">  
           <input type="text" id="idLocalNamesExample2"  
           class="form-control" placeholder="Write a character">  
         </div>  
       </div>  
       <!-- /.panel-body -->  
     </div>  
     <!-- /.panel -->  
   </div>  
   <div class="col-lg-5 col-lg-offset-2">  
     <div class="panel panel-default">  
       <div class="panel-heading">  
         Using Label & value attribute (External Source Example):  
       </div>  
       <div class="panel-body">  
         <div class="input-group">  
           <input type="text" id="idExternalNamesExample2"  
           class="form-control"  placeholder="Write a character">  
         </div>  
       </div>  
       <!-- /.panel-body -->  
     </div>  
     <!-- /.panel -->  
   </div>  
 </div>  

e) Result

  • Tapping Text into AutoComplete input   


  • Choose item from suggestion list After choosing an item from list, you will get the corresponding value:


4) Example of a MultiSelect AutoComplete :

This example show you how to handle the multiselect by using the source and select callbacks.

a) Code JavaScript


 var list = [  
       "Test",  
       "Test 2",  
       "Test 4",  
       "Example 1",  
       "Example 2"  
     ];  
     $("#idMultiSelect").autocomplete({  
       minLength: 0,  
       source: function (request, response) {  
         // delegate back to autocomplete, but extract the last term  
         response($.ui.autocomplete.filter(  
           list, extractLast(request.term)));  
       },  
       focus: function () {  
         // prevent value inserted on focus  
         return false;  
       },  
       select: function (event, ui) {  
         var terms = split(this.value);  
         // remove the current input  
         terms.pop();  
         // add the selected item  
         terms.push(ui.item.value);  
         // add placeholder to get the comma-and-space at the end  
         terms.push("");  
         this.value = terms.join(", ");  
         return false;  
       }  
     });  

b) Code Html


 <div class="panel panel-default">  
       <div class="panel-heading">  
       Multiselect Example :  
       </div>  
       <div class="panel-body">  
         <div class="input-group">  
            <input type="text" id="idMultiSelect" class="form-control" placeholder="Write a characrter">  
         </div>  
       </div>  
       <!-- /.panel-body -->  
     </div>  

c) Result


III) Summary


I hope that you appreciated my effort. Thank you for viewing my blog post, try to download the source code and do not hesitate to leave your questions and comments.

IV) History

  • v2 : Add an example using label and value attribute of source option
  • v3 : Add a new example illustrates the multi-select aspect of autoComplete.

No comments:

Post a Comment