Auto Complete with Scriptaculous
Download Code Download Scriptaculous
Overview:
Index.cfm
There are four things needed to setup the main page for auto complete.
Names.cfm
There are three things needed to send the data back to the main page.
That is the basic idea.
Code Walk Through:
Index.cfm
First, download the latest version of scriptaculous from http://script.aculo.us/. Scriptaculous comes with Prototype which is a JavaScript framework for making AJAX and Javascript easier.
In the head of the page, include the Prototype framework first and the Scriptaculous library second.
<script type="text/javascript" src="/includes/scriptaculous-js-1.6.1/prototype.js"></script>
<script type="text/javascript" src="/includes/scriptaculous-js-1.6.1/scriptaculous.js"></script>
In the body of the page, include the text box for the user to enter the text and a Div to select options from.
<input type="text" id="lastname" name="lastname_parameter" />
<div id="lastname_choices" class="name"></div>
After the text box and div, call the function that will handle the suggest list.
new Ajax.Autocompleter("firstname", "firstname_choices", "names.cfm", {});
Names.cfm
For any AJAX application I like to use cfsilent to manage white space. I usually store the output to a variable and output it on the same line at the closing cfsilent.
<cfsilent>
Since the example page uses two auto complete lists and we are using the same data file for both, let's resolve the FORM variables into a single variable.
<cfif isdefined("FORM.firstname_parameter")>
<cfset name_parameter = FORM.firstname_parameter>
<cfelseif isdefined("FORM.lastname_parameter")>
<cfset name_parameter = FORM.lastname_parameter>
<cfelse>
<cfset name_parameter = "">
</cfif>
Next, query the data. I recommend to at least limit the number of results. The are other tricks to minimize the load this causes like caching the single letter queries or only running on even number of characters.
<cfquery name="getNames" datasource="#dsn#" username="#dsnUserName#" password="#dsnPassword#">
SELECT firstname
FROM examples_names
WHERE firstname LIKE <cfqueryparam cfsqltype="cf_sql_varchar" value="#name_parameter#%">
ORDER BY firstname
LIMIT 10
</cfquery>
Finally, return the results as an unordered list. Since I limited the results to 10, I need to add a message to notify the user to refine the search further.
</cfsilent>
<ul>
<cfoutput query="getNames">
<li>#getNames.FIRSTNAME#</li>
</cfoutput>
<cfif getNames.RECORDCOUNT EQ 10>
<li>...more (refine search)</li>
</cfif>
</ul>
That is all, I was amazed how simple this was to implement the first time I did it.