jQuery Autocomplete returning multiple values

This is a quick reference for getting the jQuery autocomplete working with ColdFusion, components (CFC), a remote search method, and with the Autocomplete returning multiple values such as a name, and id and a code which may be stored in hidden fields or displayed on screen.

Download jQuery and the Autocomplete plugin

Download jQuery:

http://jquery.com/

Download the Autocomplete plugin

http://bassistance.de/jquery-plugins/jquery-plugin-autocomplete/

Create a component that performs the search

For this example we’ll perform a search on a list of country names so let’s create a component called CountryProxy.cfc. This component has a function named search():

<cffunction name="search" output="false" access="remote" returnformat="plain">
	<cfargument name="q" required="true">
	<cfargument name="limit" required="false" default="10">
	<cfset var local = {}>
	<cfquery name="local.countries" dbtype="query" maxrows="#arguments.limit#">
		select
			id,
			name,
			code
		from
			application.countries
		where
			lower(name) like <cfqueryparam cfsqltype="cf_sql_varchar" value="#lCase(arguments.q)#%">
		order by
			name
	</cfquery>
	<cfset local.result = queryToText(local.countries)>
	<cfreturn local.result>
</cffunction>

Couple of things to note:

  • The function name has access=”remote” and returnformat=”plain”. This allows the function to be called via a URL, and allows us to return our own custom formatted result
  • The main search argument must be called “q” and an optional “limit” argument may also be passed in.
  • This function is performing a “query of queries”. I’m searching a query of country names I’ve placed in the application scope. Typically your code would just access a database
  • The query is returning 3 items of data; a country id, a country name and a country code
  • The query is being converted to another format with the queryToText() function that we’ll discuss below

Returning the correct data format

The jQuery Autocomplete plugin can accept data with one “item” per line. Each item may have several attributes separated by a pipe delimiter “|”.

So for our country data we want to return data in the form:

Afghanistan|1|AF
Aland Islands|2|AX
Albania|3|AL
Algeria|4|DZ
American Samoa|5|AS
Andorra|6|AD
Angola|7|AO
Anguilla|8|AI
Antarctica|9|AQ
Antigua And Barbuda|10|AG

The first element is the country name, the second element is the country id, and the third element is the country code.

The first element will be used as the Autocomplete display value.

Convert the query to the correct format

So our queryToText() function will look something like this:

<cffunction name="queryToText" output="false">
	<cfargument name="q" required="true">
	<cfset var out = "">
	<cfloop query="q">
		<cfset out = out & q.name & "|" & q.id & "|" & q.code & chr(10)>
	</cfloop>
	<cfreturn out>
</cffunction>

Testing your component

You can check that your component is working correctly by browsing directly to it:

http://localhost/autocomplete/CountryProxy.cfc?method=search&q=a

You should see a set of countries being output to your browser. Change the q=searchterm part to test other search cases.

Implementing the Autocomplete

Within your HTML page you need to include three of your downloaded files.

Sorry about the “scr ipt” tags. The extra space prevents the blog software from marking the script tags as invalid.

<scr ipt type="text/javascript" src="jquery-1.3.2.min.js"></script>
<scr ipt type="text/javascript" src="jquery.autocomplete.min.js"></script>
<link rel="stylesheet" type="text/css" href="jquery.autocomplete.css" />

The body of your page simply needs a text field to use as the autocomplete:

<input id="country">

Then add the code to attach the autocomplete to your text field. You can use the $(document).ready() function to ensure the code only executes when the page DOM is ready.

<scr ipt type="text/javascript">
$(document).ready(function(){
	$('#country').autocomplete('CountryProxy.cfc?method=search');
});
</script>

At this point your Autocomplete should be working.

Retrieving the additional values

Currently the autocomplete is just filling your text field with the selected item name. This name is typically not very useful on it’s own, so let’s take a look at accessing the extra fields of data.

First, let’s add a div tag to the page. We’ll use this as a container to show our extra data fields:

<input id="country">
 
<div id="result"></div>

Next, we can use the Autocomplete’s result() function to access the extra values. This function is called whenever someone selects an autocomplete option.

The result() function is separately attached to the “country” text field.

<scr ipt type="text/javascript">
$(document).ready(function(){
 
	$('#country').autocomplete('CountryProxy.cfc?method=search');
 
	$('#country').result(function(event, data, formatted) {
	     if (data) {
 
	     	// Extract the data values
 
			var name = data[0];
			var id = data[1];
			var code = data[2];
 
			// Display the result
 
			$("#result").html( "<p>Name: " + name + "<br/> Id: " + id + "<br/> Code: " + code + "</p>");
		}
	});
 
});
</script>

The “result” argument is a generic event object.

The “data” argument is an array of values of the selected option.

The “formatted” argument is the formatted values that is inserted into the input field.

For this example the data values are simply displayed on the page, but they could also be placed in hidden fields if required.

Finished

At this point you should hopefully have a working Autocomplete returning multiple values.

This entry was posted in jQuery and tagged , . Bookmark the permalink. Both comments and trackbacks are currently closed.

5 Comments

  1. Posted November 26, 2009 at 7:12 am | Permalink

    I think that approach was worth a try.
    When I try it, it doesn´t work because the call to the remote service search() was garbage by an extra ‘?’.
    component [CountryProxy] has no remote function with name [search?q=q].
    Any clue?

    Obs!
    I check the component and it is working correctly by browsing directly to it.

    CFRULES

  2. frisson
    Posted December 3, 2009 at 4:56 pm | Permalink

    Hi Kevan,

    How can I change the limit to be 20?

    cheers,
    frisson

  3. Posted December 5, 2009 at 1:42 pm | Permalink

    Hi frisson

    The plugin supports a ‘max’ option:

    $(‘#country’).autocomplete(‘CountryProxy.cfc?method=search’,{max:20});

    This max value is also sent as a ‘limit’ parameter with the ajax request so you can also apply the limit to your server side code.

    See more options here:
    http://docs.jquery.com/Plugins/Autocomplete/autocomplete#url_or_dataoptions

  4. Jason Blum
    Posted May 28, 2010 at 9:46 am | Permalink

    Perfect. Thanks for sharing this.

  5. Posted April 18, 2011 at 7:42 am | Permalink

    hi expertise
    am a new bee in jquery
    how to access two values using auto complete
    index .jsp

    Employee Search :

    jQuery(function(){
    $(“#empName”). autocomplete(“list.jsp”);

    });

    am trying to fetch value from database when i select employee name i need corresponding employee id in empidhidden textbox?
    my jsp is list.jsp

    <%
    //out.print("”+strAssigneeName+”");

    }
    }
    }
    catch(Exception e)
    {
    out.println(e);
    }

    %>