Thursday, July 24, 2008

jQuery Autocomplete example

I really dig jQuery, so my experimentation with it continues. I found an excellent jQuery based autocompletion plugin from here

I created a quick and dirty aspx "servlet" page, with all the


<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="AutoCompleteTest.aspx.cs"
Inherits="jQueryAutoComplete.servlets.AutoCompleteTest" %>

Code Behind- (mine was hooked into an access db...)

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

namespace jQueryAutoComplete.servlets
public partial class AutoCompleteTest : System.Web.UI.Page
protected void Page_Init ( object sender, EventArgs e )
if ( Request.QueryString["q"] != null )
string sQry = "Select [CatID], [CatDesc] from tCategories where " +
"[CatDesc] like '" + Request.QueryString[ "q" ] + "%' order by [CatDesc]";
string oStr = ConfigurationManager.ConnectionStrings[ "cats" ].ToString ();
OleDbConnection oConn =
new System.Data.OleDb.OleDbConnection(oStr);
OleDbCommand oCmd =
new System.Data.OleDb.OleDbCommand ( sQry, oConn );
OleDbDataReader oRdr =
oCmd.ExecuteReader (
CommandBehavior.CloseConnection );
while ( oRdr.Read () )
Response.Write ( oRdr[
"CatDesc" ].ToString () + "|" +
"CatID" ].ToString ()+ Environment.NewLine);
oRdr.Dispose ();
oCmd.Dispose ();
oConn.Dispose ();
Response.End ();

And then my HTML page, which contains the simple autocomplete box which is pretty much pulled directly from the above site-

<title>jQuery Autocomplete</title>
<script src="jquery-1.2.6.pack.js" type="text/javascript"></script>
<script type='text/javascript' src='jquery.autocomplete.js'></script>
<link rel="stylesheet" type="text/css" href="jquery.autocomplete.css" />
form action="" onsubmit="return false;">
Ajax City Autocomplete:
<input type="text" id="Names" value="" style="width: 200px;" />
<input type="button" value="Get Value" onclick="lookupAjax();" />
script type="text/javascript">
findValue(li) {
if( li == null ) return alert("No match!");
// if coming from an AJAX call, let's use the CityId as the value
if( !!li.extra ) var sValue = li.extra[0];
// otherwise, let's just display the value in the text box
else var sValue = li.selectValue;
"The value you selected was: " + sValue);

function selectItem(li) {

function formatItem(row) {
return row[0] + " (id: " + row[1] + ")";

function lookupAjax(){
var oSuggest = $("#Names")[0].autocompleter;
return false;

function() {

And wa-la! Autocomplete on the fly. Thank you and jQuery.


Anonymous said...

I would like all of these features WITHOUT AJAX, that is, using a datatable, a (dynamic) array, etc.

Any thoughts?

steve_r777 @ yahoo

Anonymous said...

hey i tried your code in my simple aspx page with sql server database but it's not working.
when i load the page it is not showing any textbox.
can you just tell me why it is doing so. and i am not using linq.

python 2007 said...

hey great example,
its working fine
can you tell me how to pass more than one parameter in querystring in jquery.i want to pass two parameters at a time so could you please help me.

GroGI said...

Hi, this is a great article from a great developer. It works like a charm! Thanks for this post and keep up with the great work.

infocyde said...

@2nd Anonymous, you have to go to penoworks and download the jquery.autocomplete script, I missed mentioning that (my bad). I'm guess that is the problem.

@1st Anonymous, I've seen stuff like this done by creating a javascript array, but it kind of defeats the purporse. AJAX is a catch all term for client side communication to the server without a full page repost. You could send all the data as a javascript array object or xml data island or something like that, but then you are increasing the page size signifigantly. If you mean by not using AJAX you want to not use the XMLHTTP object that jQuery uses, you could accomplish the same thing with an iFrame (which I think some jQuery scripts default to), or maybe even a flash or silverlight object acting as your AJAX XMLHTTTP object using a socket... For the JavaScript/iFrame approach try searching the dynamic drive website (google will direct you to the exact URL).

infocyde said...

@Anonymous, here is a link to something that uses a webservice call once to bring back ALL the data and store it in a javascript array once, and then as you type it does autofill without calling back to the server. For small data loads this might be what you are after. You can skip the webservice all together and build your javascript array on the fly by looping through a dataset and a string builder and writting everything out to the javascript array though when the web page is created, but I guess that isn't as sexy as having a web service. Interesting this link does point to a way to call javascript array data through a structure similar to linq using a library called jling, might be worth a look.

Anonymous said...

I just found another way. Instead of writing to a page via Response.Write, we could just write to a HiddenField webcontrol. Then on the client side,

var data = document.getElementById("HiddenField1").value.split("\n");

infocyde said...

Cool solution with the hidden field. Thanks for posting it.

n i d h i said...

Have been trying to get the suggestions textbox work with Chinese characters. I can display it well on the page. But not in the dropdown of suggestions.