In this post I will show you how to implement the AutoCompleter plugin by Harald Kirschner. Kirschner’s AutoCompleter plugin script for MooTools provides the functionality for text suggestion and completion. It features different data-sources (local, JSON or XML), a variety of user interactions, custom formatting, multiple selection, animations and much more.
The goal of this post will be the same as the jQuery autocomplete post: Allow the user to type a few characters into a standard form text input field and to automatically provide suggestions from which the user can select.
- The latest copy of MooTools
- A server-side script that can respond to the AJAX request, in our case ColdFusion
How It Works
Once the user begins to type into the form text input field, the MooTools auto-complete is activated. After a set character length and time interval (both optional), a list of items is displayed below the input field. The user can select an item with either the arrow keys or mouse.
NB. Clicking back in the input field will repopulate the auto-complete list, if options are available, so that the user can change the selection. Deleting part of the chosen item will also trigger a new selection list.
There are three parts to this demo:
- The page’s HTML.
- The server-side code to produce the dynamic page (i.e. to load the autocomplete
divwhen the user types something into the input field).
Below is a simple ColdFusion component that takes a string as an argument. This string is part or all of the country name. The query results are parsed as an array and returned from the function, as JSON, to the MooTools auto-complete function.
<cfcomponent output="false"> <cffunction name="getCountry" access="remote" output="false" returntype="array" returnformat="json"> <cfargument name="country" type="string" required="true" /> <cfset var qryCountry = queryNew('country') /> <cfset var arrCountry = arrayNew(1) /> <cfquery name="qryCountry" datasource="test"> SELECT countryName FROM country WHERE countryName LIKE <cfqueryparam value="%#ARGUMENTS.country#%" cfsqltype="cf_sql_varchar" /> </cfquery> <cfloop query="qryData"> <cfset arrCountry[currentRow] = qryCountry.countryName[currentRow] /> </cfloop> <cfreturn arrCountry /> </cffunction> </cfcomponent>
Autocompleter.Ajax.Json event is fired. This makes a call to the ColdFusion component, which returns a JSON object of matched items. This JSON object is interpreted by the plugin and rendered as an HTML un-ordered list.
Where to Take it Next
To achieve this with the above tutorial, you will need to replace the MooTools autocomplete functionality with an ‘interim’ page that allows a user to select from a list of items, effectively turning the input field into a simple search interface. Of course, all other form field information would need to be retained between pages.
Download the Code
The example code can be downloaded from the demo page. Included are ColdFusion and PHP examples.