Auto-completion with jQuery Plugin

By mv ark

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.

Popularity  (20475 Views)
Picture
Biography - mv ark
M.V. 'Anil' Radhakrishna is a seasoned developer who enjoys working with Microsoft tools & technologies. He blogs his little discoveries and about Web development tips, tricks and trivia quite regularly. You can find some of his unusual code samples & snippets at his Code Gallery.
Create New Account
Article Discussion: Auto-completion with jQuery Plugin
mv ark posted at Friday, January 23, 2009 7:34 AM
reply
Issues
asif chouhan replied to mv ark at Wednesday, October 27, 2010 4:05 AM
Excellent article no doubt. it is easily understandable but I have some issues in my case.

1) In my case, I want ItmId, ItmCode (which is shown in list) but ItmId is must for the selected Item from the list. ItmId should not be shown in the list. Search is based on ItmCode I have gone through
selectCurrent() function of the plugin. it trigger result on two things selected.data and selected.value. Can I do something on this.

2) Can I display multi-column in dropdown list ie result of the search text.
    (For example : ItmCode,Name,Qty even ItmId which should not be shown in list.
                           xyz          Item1  10 something like this).
Plz help me out if you can. I would appreciate it.

Regards,

Asif

reply
Malay replied to asif chouhan at Wednesday, October 27, 2010 4:05 AM
Hi,

This works very well in my aspx page. However i am not able to achieve the same when I have content page with master page.

reply
Avinash Patil replied to mv ark at Wednesday, October 27, 2010 4:05 AM
Thanks for a nice article
It helped me in my custom interface implementation.


Thanks & Regards 
reply
Chris replied to mv ark at Wednesday, October 27, 2010 4:05 AM
Very helpful example!  The only change I would suggest is to paramterize the command to prevent SQL injection.
reply
Phil replied to Malay at Wednesday, October 27, 2010 4:05 AM
Make sure if you are using a Master Page you are using the actual ID of what your control renders when viewed.  Take a peek at your page source and you should see the actual ID.
reply
Rob replied to mv ark at Wednesday, October 27, 2010 4:05 AM
Very good article.

I was wondering though, how do I pull across the value of a variable from an aspx.vb/cs page to be used in the sql statement?

Many thanks.
reply
steve harris replied to asif chouhan at Wednesday, October 27, 2010 4:05 AM
i want to do something similar, did this get resolved or was there any help added to show how exactly ?
reply
crap replied to mv ark at Wednesday, October 27, 2010 4:05 AM
besides the obvious security holes in the code, will this scale for anything beyond a handful of users
reply
Wasim replied to mv ark at Wednesday, October 27, 2010 4:05 AM
Hi,

This is probably too old, but anyways. Looking at the Search Page Replacement example here: http://docs.jquery.com/Plugins/Autocomplete

How would i return the 2 values (title & url) from the handler and use them from the js code accordingly?

Hope I can get a response to this.

Thanks
Wasim
reply