jQuery AutoComplete

In this post I would show how to use jQuery AutoComplete plug-in. Auto-complete takes input from the user, and returns a list of words that match the users input.

You could download jQuery AutoComplete plug-in from the following link: http://bassistance.de/jquery-plugins/jquery-plugin-autocomplete/

Below I am calling a web handler "select.ashx" which returns values/list based on text user
types (prefix text) in the textbox.

Aspx Markup:

<asp:TextBox ID="txtAutoComplete" runat="server" />

jQuery AutoComplete calling web handler:

   1: <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js" type="text/javascript"></script>
   2:    <script src="jquery.autocomplete.min.js" type="text/javascript"></script>
   3:   <script type="text/javascript">
   4:    $(document).ready(function () {
   5:      $("#<%=txtAutoComplete.ClientID %>").autocomplete('select.ashx');
   6:   });
   7:   </script>

Below is the web handler which returns the auto complete list: 

 

   1: using System;
   2: using System.Collections.Generic;
   3: using System.Web;
   4:  
   5:     /// <summary>
   6:     /// Summary description for handler "select"
   7:     /// </summary>
   8: public class select : IHttpHandler
   9: {
  10:  
  11:     public void ProcessRequest(HttpContext context)
  12:     {
  13:         if (!String.IsNullOrEmpty(context.Request.QueryString["q"]))
  14:         {
  15:             foreach (string s in GetAutoCompleteValues(context.Request.QueryString["q"]))
  16:             {
  17:                 context.Response.Write(s + Environment.NewLine);
  18:             }
  19:         }
  20:  
  21:     }
  22:     public static string[] GetAutoCompleteValues(string prefixText)
  23:     {
  24:         List<string> myList = new List<string> { "Alicia", "Steven", "Stephany", "Robert", "Johanne" };
  25:         List<string> autoCompleteList = new List<string>();
  26:         foreach (string s in myList)
  27:         {
  28:             if (s.ToUpper().Contains(prefixText.ToUpper()))
  29:             {
  30:                 autoCompleteList.Add(s);
  31:             }
  32:         }
  33:         return autoCompleteList.ToArray();
  34:     }
  35:  
  36:     public bool IsReusable
  37:     {
  38:         get
  39:         {
  40:             return true;
  41:         }
  42:     }
  43: }

 

When your run the above code and start typing say for example ā€œsā€, you would see the following output:

image

There are many optional options available to configure the auto complete. Some of which
I discuss here:

minChars: 2

It is the minimum number of characters a user has to type before the auto complete
activates.

extraParams: {"p1":"1","p2":"2"}

If you want to send extra params along with your auto complete you can use this
option. Here I am sending param "p1" as 1 and param "p2" as 2. You can access these params in the above handler as:

string param1 = context.Request.QueryString["p1"];
string param2 = context.Request.QueryString["p2"];

 

 

formatItem:function(data, i, total){ 
return data[0];
}

 

Provides advanced markup for an item. For each row of results, this function will be
called. Parameters to this function: the results row, the position of the row in the
list of results (starting at 1),the number of items in the list of results.

formatResult:function(data) {             
return data[0];
}

Similar to formatItem, but provides the formatting for the value to be put
into the input field.

multiple: true 

Another useful parameter sometime if you want to have multiple values in your
textbox. The above param indicates whether to allow more than one auto completed-value to enter. So with above parameter you could start typing one value, select that value, a comma is inserted automatically, and you could start typing again for other value. Example:

image 

multipleSeparator:", "

Separator to put between values when using multiple option.

 

 

More set of options you could find in this link:
http://docs.jquery.com/Plugins/Autocomplete/autocomplete#url_or_dataoptions

You could also find which value from the auto complete the user clicked.
Say you want to update a label when the user selected a particular value from
auto complete. You could use the following code along with the aboce to do so:

   1: $("#<%=txtAutoComplete.ClientID %>").result( function findValueCallback(event, data, formatted)
   2:         {    
   3:           if(data)
   4:           {
   5:             $('#<%=lbl.ClientID %>').text("You Selected: "+ data[0]);
   6:           }            
   7:         });

 

So here is the entire jQuery code along with the some of options that I discussed above:

   1:  
   2:     $(document).ready(function () {
   3:      $("#<%=txtAutoComplete.ClientID %>").autocomplete('select.ashx', {
   4:             minChars: 2,
   5:             extraParams: {"p1":"1","p2":"2"},
   6:             formatItem:function(data, i, total) {             
   7:              return data[0];          
   8:             },
   9:             formatResult:function(data) {             
  10:              return data[0];
  11:             },
  12:             multiple: true,
  13:             multipleSeparator:", "  
  14:         });
  15:       
  16:         $("#<%=txtAutoComplete.ClientID %>").result( function findValueCallback(event, data, formatted)
  17:         {    
  18:           if(data)
  19:           {
  20:             $('#<%=lbl.ClientID %>').text("You Selected: "+ data[0]);
  21:           }            
  22:         });
  23:      });

Note: You could also use a web service/wcf service/code behind web method to return the list of items. Also you could write code that returns list of items from your database.

Hope anyone find this information useful.

5 Comments

Comments have been disabled for this content.