Sunday 26 February 2012

JQuery Autocomplete Using ColdFusion CFCs

I recently had to create a form text field that used jQuery autocomplete on a ColdFusion website and I thought it was pretty cool the way it worked so I thought I would share. Here it is in action...


This form can be broken into 3 fairly simple parts: The basic HTML that displays the form, the CFC that queries the database and the jQuery that ties it all together. Let's start off by looking at the form code...
Nothing to see here really, just an input text field and a submit button that doesn't do anything yet. Next up is the CFC we use to query the database...

The queryNames function is fairly similar to any other function you might write to query a database except it limits the amount of rows returned to 10. If you don't do this your autocomplete list will come out too long and could possibly take a while to load if you have a lot of rows in your table.

And finally we bring the two together with jQuery...

Here we use Ajax to call the queryNames method in our cfc, passing in the current value of the text field, then jQuery uses the response to populate the autocomplete widget. Pretty cool, huh?

Hope this helped!