Jquery autocomplete with Coldfusion

My main type of coding with coldfusion is using tags.
I had seen Ray Camden's blog about how to use jquery autcomplete with coldfusion, but he had it using cfscript.
A person in the comments left a link to how to do it tag based; although, the proposed solution was a bit rough, it gave me an idea on how to make this work.

Here's what I came up with.

First, I added the jquery and UI script; then, I added the code to $(document).ready function so it will always be available:

$(document).ready(function() {  
//use for autocomplete minimun length
        function split( val ) {
            return val.split( /,\s*/ );
        function extractLast( term ) {
            return split( term ).pop();
        // autocomplete function   
            source: "emp.cfc?method=searchUserByName",
            select:function(event,ui) {
            search: function() {
                    // custom minLength
                    var term = extractLast( this.value );
                    if ( term.length < 3 ) {
                        return false;
        // clear search box and hidden uid box
        $("#fullname").change(function(e) {
            if($(this).val() == "") {

And here's my CFC call

I set the return format to JSON instead of passing it through jquery url call.
'TERM' is what coldfusion passed for the 'search/fullname' input box call (it took me awhile figuring this out).
Since I use 'full_name' field as return call, sometimes it's blank, so I used SQL isNull to set a default.

<cffunction access="remote" name="searchUserByName" returnformat="JSON">
<cfargument name="term" required="yes">

<cfset empArray="ArrayNew(1)">

<cfquery datasource="#application.ds#" name="qryUsers">
select uid, isNull(full_name,'NO NAME') as full_name
 from users
 where full_name like <cfqueryparam cfsqltype="cf_sql_varchar" value="%#arguments.term#%">
order by full_name

<cfloop query="qryUsers">
    <cfset empStruct = StructNew() />
    <cfset empStruct["id"] = uid />
    <cfset empStruct["label"] = full_name />

    <cfset ArrayAppend(empArray,empStruct) />

<cfreturn empArray />


And that's it!


Post a Comment
Leave this field empty

Required Field