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

http://www.pengoworks.com/workshop/jquery/autocomplete.htm

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

aspx-

<%@ 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 ();
System.Data.OleDb.
OleDbConnection oConn =
new System.Data.OleDb.OleDbConnection(oStr);
oConn.Open();
System.Data.OleDb.
OleDbCommand oCmd =
new System.Data.OleDb.OleDbCommand ( sQry, oConn );
System.Data.OleDb.
OleDbDataReader oRdr =
oCmd.ExecuteReader (
CommandBehavior.CloseConnection );
while ( oRdr.Read () )
{
Response.Write ( oRdr[
"CatDesc" ].ToString () + "|" +
oRdr[
"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-

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<
html>
<
head>
<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" />
</
head>
<
body>
<
form action="" onsubmit="return false;">
<p>
Ajax City Autocomplete:
<input type="text" id="Names" value="" style="width: 200px;" />
<input type="button" value="Get Value" onclick="lookupAjax();" />
</p>
</
form>
<
script type="text/javascript">
function
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;
alert(
"The value you selected was: " + sValue);
}

function selectItem(li) {
findValue(li);
}

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

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

$(document).ready(
function() {
$(
"#Names").autocomplete(
"AutoCompleteTest.aspx",
{
delay:5,
minChars:1,
matchSubset:1,
matchContains:1,
cacheLength:10,
onItemSelect:selectItem,
onFindValue:findValue,
formatItem:formatItem,
autoFill:
true
}
);
});
</script>
</
body>
</
html>


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

9 comments:

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.

http://www.xcite.ch/?p=63

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");
$("#TextBox1").autocomplete(data);

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.