March

18

jQuery UI Autocomplete Widget with ColdFusion

You may also be interested in the jQuery UI Autocomplete Widget with PHP and MySQL or the jQuery UI Autocomplete Widget with ASP.NET VB post. Also, check out the Using jQuery Autocomplete to Populate Another Autocomplete post.

The jQuery UI folks have released an autocomplete widget that is pretty slick. Using it with ColdFusion is a snap. This example uses the serializeJSON function in ColdFusion 8. If you have an earlier version of CF, you will have to find a cfc that can build a JSON string for you. There are several freely available cfc’s that do it for you.
autocomplete
This example will use US states and territories to populate the autocomplete. It will also demostrate how to fill other fields with data returned from the database. This data can be used to fill a visible text box or a hidden form field. It also demonstrates the basic autocomplete functionality which may be fine for some applications.

Of course, you will need the jQuery core file, the jQuery UI core file, and the jQuery UI style sheet of choice. The style sheet comes from the themes available in the jQuery UI website and can be downloaded with the core file:

<link type="text/css" href="jquery-ui-1.8rc3.custom.css" rel="stylesheet" /> 

<script type="text/javascript" src="jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="jquery-ui-1.8rc3.custom.min.js"></script>

The HTML is straight forward and stripped down for the example:

<form action="index.cfm"  method="post">
<fieldset>
<legend>jQuery UI Autocomplete Example - ColdFusion Backend</legend>
<p>Start typing the name of a state or territory of the United States</p>
<p class="ui-widget"><label for="state">State (abbreviation in separate field): </label>
	<input type="text" id="state"  name="state" /> <input readonly="readonly" type="text" id="abbrev" name="abbrev" maxlength="2" size="2"/></p>
    <input type="hidden" id="state_id" name="state_id" />
<p class="ui-widget"><label for="state_abbrev">State (replaced with abbreviation): </label>
<input type="text" id="state_abbrev" name="state_abbrev" /></p>
<p><input type="submit" name="submit" value="Submit" /></p>
</fieldset>
</form>

As a bonus, we dump out the form values to see what we have right underneath the form itself:

<cfdump var="#form#" label="Form Fields" />

And the jQuery on the page is equally brief:

$(function() {

            $('#abbrev').val("");

            $("#state").autocomplete({
                source: "states.cfm",
                minLength: 2,
                select: function(event, ui) {
                    $('#state_id').val(ui.item.id);
                    $('#abbrev').val(ui.item.abbrev);
                }
            });

            $("#state_abbrev").autocomplete({
                source: "states_abbrev.cfm",
                minLength: 2
            });
        });

Notice that there are two autocomplete functions on the page, one for each example in the demo. Each function calls a different ColdFusion file which return slightly different result sets.

Also, the minLength for autocomplete to return results is set to 2 to prevent too many rows from being returned.

Both ColdFusion pages return the data after a few steps:

  1. It queries the database
  2. Loops the query, adding each row to a structure that is appended to an array
  3. Outputs the array as JSON data

The states.cfm file returns the id field, the state field as ‘label’, and the abbrev field. These values are placed in the appropriate text boxes by the autocomplete jQuery function.

<cfset returnArray = ArrayNew(1) />

<cfquery name="qryStates" dataSource="autocomplete">
    Select * from states where state like '%#URL.term#%'
</cfquery>

<cfloop query="qryStates">
    <cfset statesStruct = StructNew() />
    <cfset statesStruct["id"] = id />
    <cfset statesStruct["label"] = state />
    <cfset statesStruct["abbrev"] = abbrev />

    <cfset ArrayAppend(returnArray,statesStruct) />
</cfloop>

<cfoutput>
#serializeJSON(returnArray)#
</cfoutput>

Unfortunately, the ColdFusion function serializeJSON does not put query results in the format that javascript likes. That’s why we have to do the hokey-pokey with the structure and array.

The states_abbrev.cfm shows the basic functionality of the autocomplete function by just assigning results of the query to the ‘label’ and ‘value’ fields. Explanation on the ‘label’ and ‘value’ fields from the jQuery UI site:

“The local data can be a simple Array of Strings, or it contains Objects for each item in the array, with either a label or value property or both. The label property is displayed in the suggestion menu. The value will be inserted into the input element after the user selected something from the menu. If just one property is specified, it will be used for both, eg. if you provide only value-properties, the value will also be used as the label.”

<cfset returnArray = ArrayNew(1) />

<cfquery name="qryStates" dataSource="autocomplete">
    Select * from state where state like '%#URL.term#%'
</cfquery>

<cfloop query="qryStates">
    <cfset statesStruct = StructNew() />
    <cfset statesStruct["label"] = state />
    <cfset statesStruct["value"] = abbrev />

    <cfset ArrayAppend(returnArray,statesStruct) />
</cfloop>

<cfoutput>
#serializeJSON(returnArray)#
</cfoutput>

Usual recommended jQuery and CF reading:

Demo

 

Further Reading:

  1. Using jQuery Autocomplete to Populate Another Autocomplete – ASP.NET, ColdFusion, and PHP Examples
  2. jQuery UI Autocomplete Widget with ASP.NET VB
  3. jQuery UI Autocomplete Widget with PHP and MySQL
  4. jQuery.ajax and jQuery.post Form Submit Examples with ColdFusion
  5. ColdFusion Example: Session Timeout Warning with jQuery/JS

5 Comments for jQuery UI Autocomplete Widget with ColdFusion


Kevin
April 2, 2010

You may want to *also* include a CFSCRIPT version of the CF code because it's more Javascripty (execept the '=' signs) and easier to read…

<CFSCRIPT>
aItems = [];
for (i=1, i <= qryState.recordCount, i++) {
item = {
label = qryState.state
, value = qryState.abbrev
};
arrayAppend( aItems, item );
}
writeOutput( serializeJSON(aItems) );
</CFSCRIPT>


ShinyStar
April 23, 2010

Hi,

I am getting empty string, when I try to read out a value of a first text box which I am using as a URL param for second text box.Any clues.code as follows.

$(function() {
$("#department").autocomplete({
source: "test2.cfm"
});
$("#location").autocomplete({
source: "test2.cfm?department="+$("#department").val() // Value in the department text box need to get here & results need to be filtered based on Department
});
});

<form name="frm" action="test.cfm" method="post">
Department: <input id="department" />
Location: <input id="location" />

</form>


jen
April 24, 2010

@ShinyStar
You need to assign the value field (not .val) of the local returned data to your URL param. I would assign to a variable if it cannot be used directly by the next autocomplete. Or, you could just wait and see what the coldfusionjedi Raymond Camden says.


Pritesh
May 29, 2010

Try below coldfusion wrapper which doesn't require any kind of javascript to be written

http://www.thecfguy.com/post.cfm/coldfusion-wrapper-for-jquery-autocomplete

hope you like it.


jen
May 30, 2010

@Pritesh
Nice work.

@ShinyStar
I followed up with a post on multiple autocompletes here:
http://www.jensbits.com/2010/05/29/using-jquery-autocomplete-to-populate-another-autocomplete-asp-net-coldfusion-and-php-examples/

Leave a comment

Why ask?

 

« | »