Auto-completion with jQuery Plugin

jQuery has taken the Web development world by storm. jQuery Plugins simplify building complex functionality for your web pages. This article shows how to implement the Autocomplete feature with a textbox.

As the jQuery website proclaims: "jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development". It's philosophy of "write less, do more" has attracted companies like Google, Amazon, Nokia, BBC to embrace it for their web properties. Besides it's ease of use & low footprint, the biggest benefit is that it let's you write cross browser code(jQuery supports these browsers: Firefox 1.5+, Internet Explorer 6+, Safari 3+, Opera 9+). A few months ago, Microsoft has adopted jQuery as part of it's official application development platform & there will be full-fledged support with Visual Studio (which will include jQuery intellisense, snippets, examples, and documentation).

A jQuery plugin is reusable jQuery code encapsulating complex functionality packaged into a JavaScript file.  There are hundreds of jQuery plugins built by the jQuery Community.  I was amazed at the ease with which you can implement the auto-completion feature for textboxes with the jQuery Autocomplete plugin. All the grunt work is done by the jQuery Autocomplete Plugin & there is hardly any code to write.

Auto-completion of search terms is an AJAX feature  popularized by Google that reduces typing by listing possible keywords as the user types.


This article will show you the steps with a simple ASP.NET sample based on a generic example mentioned in the Autocomplete Plugin documentation and an interesting answer on an online Forum about the plugin. The sample allows users to type first-names of people to search for and as they type a character the Autocomplete plugin starts searching for matching entries from a table that contains names (you can connect to Pubs or Northwind database on SQL Server) and displays a list of values to choose from. By entering more characters, the user can filter down the list to better matches.

Here are the steps to build the sample:
1) You will need to download the following external files from the mentioned URLs -
The parent jQuery library  - http://code.jquery.com/jquery-latest.js
CSS from the original demo - http://dev.jquery.com/view/trunk/plugins/autocomplete/jquery.autocomplete.css
JS file representing the Autocomplete Plugin - http://dev.jquery.com/view/trunk/plugins/autocomplete/jquery.autocomplete.js

Create a blank website using Visual Studio & drop these files into seperate folders named JS & CSS. We will reference these files later in our code.

2) Add a blank inline (without code-behind) .ASPX page in Visual Studio, name it say, Search.aspx. Copy the following code into it -

<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html>
<head>
<title>Autocomplete using jQuery Plugin</title>
<script src="js/jquery-latest.js" type="text/javascript"></script>
<link rel="stylesheet" href="css/jquery.autocomplete.css" type="text/css" />
<script type="text/javascript" src="js/jquery.autocomplete.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#fname").autocomplete("AutocompleteData.ashx");
});
</script>

</head>
<body>
Search: <input id="fname" type="text" />
</body>
</html>

This page essentially has a text box. We reference this text box with it's ID using jQuery & use the autocomplete() method on it. The definition of autocomplete() method is in the external JavaScript file jquery.autocomplete.js

This method can take upto 2 arguments. Here is a small description of it from the online documentation -
autocomplete( url or data, [options] )

The first argument can be an URL for remote data or an an array for local data.

For remote data: When the user starts typing, a request is send to the specified backend ("my_autocomplete_backend.php"), with a GET parameter named q that contains the current value of the input box and a parameter "limit" with the value specified for the max option.

A value of "foo" would result in this request url: my_autocomplete_backend.php?q=foo&limit=10

The result must return with one value on each line. The result is presented in the order the backend sends it.


Note the last line, it say's "The result must return with one value on each line". Rather than write an .ASPX page to fetch the values to display for the auto-completion list, we shall use a Generic Handler to conserve resources. Generic handlers have an extension of ASHX.

To keep the example simple, I have ignored the optional argument that let's you customize other properties of the auto-completion list.

Notice that we are calling the Generic Handler named AutocompleteData.ashx with the autocomplete() method  in our example -
$("#fname").autocomplete("AutocompleteData.ashx");

Now onto the AutocompleteData.ashx....

3) In Visual Studio, select Generic Handler file type after you choose "Add New Item" by right clicking on the website in Solution Explorer

Paste the following code into it and modify the connection string and query to fetch the first name of employees -

<%@ WebHandler Language="C#" Class="AutocompleteData" %>

using System;
using System.Web;
using System.Data.SqlClient;

public class AutocompleteData : IHttpHandler {

public void ProcessRequest (HttpContext context) {
string firstname = context.Request.QueryString["q"];
string sql = "select top 10 firstname from Employee where firstname like '" + firstname + "%'";

using (SqlConnection connection = new SqlConnection("_place_your_connection_string_here"))
using (SqlCommand command = new SqlCommand(sql, connection))
{
connection.Open();

using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
context.Response.Write(reader.GetString(0) + Environment.NewLine);
}
}
}
}

public bool IsReusable {
get {
return false;
}
}

}



4) Hit F5 to run the program and watch the auto completion list in action, by typing some characters into the textbox.

ASP.NET developers typically use the AutoComplete Extender that is the part of the ASP.NET AJAX Control Toolkit to plug it to a text box to implement auto-completion. The jQuery Autocomplete Plugin is a very attractive alternative.

By mv ark   Popularity  (30771 Views)