Using jQuery Auto-Complete with ColdFusion

Creating an autocomplete form field historically has not been a trivial matter and would require an indepth knowledge of JavaScript and CSS. However, the task is made far more simple when using one of the many freely-available JavaScript libraries. In this post I will show you how to implement the jQuery Autocomplete created by Dylan Verheul.

The Goal

Allow the user to type a few characters into a standard form text input field and to automatically provide suggestions from which the user can select.

Prerequisites

  1. The latest copy of jQuery
  2. A basic understanding of JavaScript
  3. A server-side script that can respond to the AJAX request, in our case ColdFusion

Demo

The demo will specifically look at a simple form text input field, which takes a country name.

See the demo, and others, in action

How It Works

Once the user begins to type into the form text input field, the jQuery autocomplete is activated. After a set time interval, a list of items is displayed below the input field. The user can select these with either the arrow keys or mouse.

The Code

There are three parts to this demo:

  1. The page’s HTML.
  2. The server-side code to produce the dynamic page (i.e. to load the autocomplete div when the user types something into the input field).
  3. The jQuery & JavaScript.

HTML Form

<h3>Example 1.: Country Lookup</h3>
<p>Using <abbr title="Asynchronous JavaScript and XML">AJAX</abbr> to interrogate the database.</p>
<p>Example data: Australia, Bulgaria, United Kingdom</p>
<form name="frmAutoCompleteCountry" id="frmAutoCompleteCountry" action="#" method="post">
<p>
<label for="country">Country</label>
<input type="text" name="country" id="country" />
</p>
</form>
<p>NB. If you have <a href="http://getfirebug.com/" title="Get Firebug">Firebug</a> installed you will be able to view the <abbr title="Asynchronous JavaScript and XML">AJAX</abbr> call.</p>

ColdFusion

This is a simple example, using a database to return a list of country names that match the characters the user has input. You could expand this and return a JSON data structure.

<cfsetting enablecfoutputonly="true">
<cfquery name="qryGetCountry" datasource="myDatasource">
SELECT countryName
FROM Country
WHERE countryName LIKE <cfqueryparam value="#URL.q#%" cfsqltype="cf_sql_varchar" />
</cfquery>
<cfoutput query="qryGetCountry">
#qryGetCountry.countryName##chr(10)#
</cfoutput>

JavaScript

The JavaScript will attach itself after the document is ready, i.e. after the page has loaded. Each time the text input field, with the ID of country, is changed, the autocomplete event is fired. This makes a call to the ColdFusion page, which returns a list of matched items.

<script type="text/javascript" src="jquery-1.2.6.min.js"></script>
<script type="text/javascript" src="jquery.autocomplete.js"></script>
<link type="text/css" href="autocomplete.css" rel="stylesheet" media="screen" />
<script type="text/javascript">
$(document).ready(function() {
	$("#country").autocomplete(
		"country.cfm",
		{
			minChars:2,
			delay:200,
			autoFill:false,
			matchSubset:false,
			matchContains:1,
			cacheLength:10,
			selectOnly:1
		}
	);
);
</script>

Where To Take It Next

JSON

The above example only shows a simple text list, separated by carriage returns. It is more preferable to use JSON.

Unobtrusive JavaScript

As with any page that is loaded with JavaScript and AJAX functionality, it should work without JavaScript.

To achieve this with the above tutorial, you will need to replace the jQuery autocomplete functionality with an ‘interim’ page that allows a user to select from a list of items, effectively turning the input field into a simple search interface. Of course, all other form field information would need to be retained between pages.

Download The Code

The example code can be downloaded from the demo page. Included are ColdFusion and PHP examples.


Bookmark:

  • Digg
  • del.icio.us
  • Technorati
  • StumbleUpon
  • Google
  • Ma.gnolia
  • YahooMyWeb
  • Facebook
  • Reddit
  • BlinkList
  • blogmarks
  • Fark
  • Furl
  • Simpy
  • Slashdot
  • Spurl
  • Wists
  • NewsVine
  • Pownce

Tags: , , , , , , ,

“Fantástico”, as we say in Portuguese ;)

The successor to Dylan’s autocomplete plugin can be found here: http://plugins.jquery.com/project/autocompletex

There are a few API changes and a ton of improvements and new features (eg. multiple complete ala GMail to-field).

May be worth a try!

Simon, thanks for posting this code. I see the potential of it, but I keep getting “Unknown runtime error” messages in JavaScript over and over. I’m trying to call a ColdFusion page and even just tried to repeat your example, but still get issues.

@bernie it’s a little difficult to debug, but you’ll need to make sure that

1. The data is returned in the correct format
2. The cfm file that the auto-complete javascript calls is accessible
3. That you’re using the url.q variable in your query

Yeah it is difficult to debug, although Firebug makes it a bit easier. It’s finding the CFM page and I have been able to verify that it’s passing in url.q correctly. For some reason, an Access version of my query works as well, but the Oracle query doesn’t. Also, it only seems to work in Firefox for me, versus IE and Firefox for you. I’ll give it a couple more tries and give it up today if I can’t get it worked out.

Thanks!

Duh Simon, I had forgotten to add LOWER() to my Oracle query…*slap self*…now it works in 100% in Firefox, but not in IE. Since IE is the version my customers use, I have to figure out why I keep getting the runtime errors there…

Simon - I’m using Coldfusion and can’t get this to work. I don’t get any errors but it doesn’t auto complete either. I am missing something but not sure what.

I put this in the index.cfm page and have country.cfm and all the js and css file(s) in the same directory:

Auto Complete - jQuery

$(document).ready(function() {
$(”#country”).autocomplete(
“country.cfm”,
{
minChars:2,
delay:200,
autoFill:false,
matchSubset:false,
matchContains:1,
cacheLength:10,
selectOnly:1
}
);
);

Example 1.: Country Lookup
Using to interrogate the database.
Example data: Australia, Bulgaria, United Kingdom

Country

opps. i should know better. my question is what should the index.cfm file contain? I think my country.cfm is ok. Thanks!

@Bob The complete code is provided for download. Everything you need is contained within.

Thanks Simon - I did get it to work.
Follow up question -

If the user types in: ’street main’ in the search box,
I would like ‘123 main street’ to be returned as a result.

Are there settings to allow that?

Thanks!

@Bob.

Your request is a little complicated. If you want to find every instance that is like ‘main street’, you will need to amend your database query to include the wildcard operator %.

e.g.

SELECT column1, column2
FROM tableName
WHERE column1 LIKE ‘%#URL.q#%’

Obviously you need to substitute the query for your own and make sure you use cfqueryparam around the variable.

If you want to return anything that contains the words ‘main’ and or ’street’, you will have to enable full text searching on your database column (if using MSSQL). Using full text searching is a whole different topic that I’ll not go into here.

Thanks Simon…
I was thinking something like this to “return anything that contains the words ‘main’ and ’street’”.
Treat url.q as a list, separated by spaces, and loop through the list

Would that work?

select column1, column2
from tableName
where 1=1

and upper(column1) LIKE