In a previous post, I demonstrated how to implement Dylan Verheul’s jQuery Autocomplete plugin. Not content with demonstrating one library’s plugin, it is now the turn of MooTools.

MooTools is a compact, modular, Object-Oriented JavaScript framework designed for the intermediate to advanced JavaScript developer. It allows you to write powerful, flexible, and cross-browser code with its elegant, well documented, and coherent API.

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

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.

Prerequisites

  1. The latest copy of MooTools
  2. A basic understanding of JavaScript and JSON
  3. A server-side script that can respond to the AJAX request, in our case ColdFusion

Demo

The demo below will show how to interact with a simple ColdFusion script, but I’ll also provide more (advanced) examples in the download.

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.

The Code

There are three parts to this demo:

  1. The page’s HTML.
  2. The server-side code to produce the dynamic page (i.e. to load the autocomplete div when the user types something into the input field).
  3. The MooTools JavaScript.

HTML Form

<h1>Example: Country Lookup</h1>
<p>Using <abbr title="Asynchronous JavaScript and XML">AJAX</abbr> to interrogate the database.</p>
<p>Example data: Australia, Bulgaria, United Kingdom</p>
<form name="frmAutoCompleteCountry" id="frmAutoCompleteCountry" action="#" method="post">
<p>
<label for="country">Country</label>
<input type="text" name="country" id="country" />
</p>
</form>

ColdFusion

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>

JavaScript

The JavaScript will attach itself after the DOM is ready — this more or less relates to when the page has loaded in the browser. Each time the text input field, with the ID of country, is changed, the 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.

<script type="text/javascript" src="mootools.js"></script>
<script type="text/javascript" src="Observer.js"></script>
<script type="text/javascript" src="Autocompleter.js"></script>
<link rel="stylesheet" href="Autocompleter.css" type="text/css" media="screen" />
<script type="text/javascript">
window.addEvent('domready', function() {
	new Autocompleter.Ajax.Json(
		'country',
		'data/Country.cfc?method=getCountry&returnformat=json&country=' + $('country').getProperty('value')
		, {
			'minLength': 1, // We wait for at least one character
			'overflow': true // Overflow for more entries'
	});
});
</script>

Where to Take it Next

Unobtrusive JavaScript

As with any page that is loaded with JavaScript and AJAX functionality, it should work without JavaScript.

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.

Creating an autocomplete form field historically has not been a trivial matter and would require an indepth knowledge of JavaScript and CSS. However, the task is made far more simple when using one of the many freely-available JavaScript libraries. In this post I will show you how to implement the jQuery Autocomplete created by Dylan Verheul.

The Goal

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.

Prerequisites

  1. The latest copy of jQuery
  2. A basic understanding of JavaScript
  3. A server-side script that can respond to the AJAX request, in our case ColdFusion

Demo

The demo will specifically look at a simple form text input field, which takes a country name.

See the demo, and others, in action

How It Works

Once the user begins to type into the form text input field, the jQuery autocomplete is activated. After a set time interval, a list of items is displayed below the input field. The user can select these with either the arrow keys or mouse.

The Code

There are three parts to this demo:

  1. The page’s HTML.
  2. The server-side code to produce the dynamic page (i.e. to load the autocomplete div when the user types something into the input field).
  3. The jQuery & JavaScript.

HTML Form

<h3>Example 1.: Country Lookup</h3>
<p>Using <abbr title="Asynchronous JavaScript and XML">AJAX</abbr> to interrogate the database.</p>
<p>Example data: Australia, Bulgaria, United Kingdom</p>
<form name="frmAutoCompleteCountry" id="frmAutoCompleteCountry" action="#" method="post">
<p>
<label for="country">Country</label>
<input type="text" name="country" id="country" />
</p>
</form>
<p>NB. If you have <a href="http://getfirebug.com/" title="Get Firebug">Firebug</a> installed you will be able to view the <abbr title="Asynchronous JavaScript and XML">AJAX</abbr> call.</p>

ColdFusion

This is a simple example, using a database to return a list of country names that match the characters the user has input. You could expand this and return a JSON data structure.

<cfsetting enablecfoutputonly="true">
<cfquery name="qryGetCountry" datasource="myDatasource">
SELECT countryName
FROM Country
WHERE countryName LIKE <cfqueryparam value="#URL.q#%" cfsqltype="cf_sql_varchar" />
</cfquery>
<cfoutput query="qryGetCountry">
#qryGetCountry.countryName##chr(10)#
</cfoutput>

JavaScript

The JavaScript will attach itself after the document is ready, i.e. after the page has loaded. Each time the text input field, with the ID of country, is changed, the autocomplete event is fired. This makes a call to the ColdFusion page, which returns a list of matched items.

<script type="text/javascript" src="jquery-1.2.6.min.js"></script>
<script type="text/javascript" src="jquery.autocomplete.js"></script>
<link type="text/css" href="autocomplete.css" rel="stylesheet" media="screen" />
<script type="text/javascript">
$(document).ready(function() {
	$("#country").autocomplete(
		"country.cfm",
		{
			minChars:2,
			delay:200,
			autoFill:false,
			matchSubset:false,
			matchContains:1,
			cacheLength:10,
			selectOnly:1
		}
	);
);
</script>

Where To Take It Next

JSON

The above example only shows a simple text list, separated by carriage returns. It is more preferable to use JSON.

Unobtrusive JavaScript

As with any page that is loaded with JavaScript and AJAX functionality, it should work without JavaScript.

To achieve this with the above tutorial, you will need to replace the jQuery 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.

In my first post in this series, I introduced Using JavaScript Arithmetic Operators in ColdFusion 8. Now we’ll concentrate on Assignment operators.

An assignment operator assigns a value to its left operand based on the value of its right operand.

The basic assignment operator is equal (=), which assigns the value of its right operand to its left operand. That is, x = y assigns the value of y to x. The other assignment operators are usually shorthand for standard operations, as shown in the following table.

Operator Shorthand operator Meaning
+= x += y x = x + y
-= x -= y x = x - y
*= x *= y x = x * y
/= x /= y x = x / y
%= x %= y x = x % y

In unusual situations, the assignment operator is not identical to the Meaning expression in the above table. When the left operand of an assignment operator itself contains an assignment operator, the left operand is evaluated only once. For example:

<cfscript>
a[i++] += 5 //i is evaluated only once
a[i++] = a[i++] + 5 //i is evaluated twice
</cfscript>

An often mentioned complaint by ColdFusion developers is the lack of operators commonly found in other programming languages such as JavaScript. For example, instead of the greater-than (>) symbol we have been restricted to the more wordy GT or GREATER THAN operator. However, in ColdFusion 8 this has changed and we have more freedom to use familiar JavaScript operators in <cfscript> blocks.

In the following series of posts, I will introduce the changes and show some simple examples. The first in the series is Arithmetic Operators.

Arithmetic operators take numerical values (either literals or variables) as their operands and return a single numerical value. The standard arithmetic operators are addition (+), subtraction (-), multiplication (*), and division (/). These haven’t changed from ColdFusion version 7 to 8.

A key change comes with the use of Unary Operators. The unary operators require only one operand; they perform various operations such as incrementing/decrementing a value by one, negating an expression, or inverting the value of a boolean.

These operators work as they do in most other programming languages.

% (Modulus)

The modulus operator is used as follows:

var1 % var2

The modulus operator returns the first operand modulo the second operand, that is, var1 modulo var2, in the preceding statement, where var1 and var2 are variables. The modulo function is the integer remainder of dividing var1 by var2. For example, 12 % 5 returns 2.

In ColdFusion this is written:

<cfif myQuery.currentRow % 2></cfif>

A good use of the modulus operator would be to alternate row colours in tabular data. The above code could be wrapped around a CSS class, dynamically changing the name of the class on each row iteration.

++ (Increment)

The increment operator is used as follows:

var++ or ++var

This operator increments (adds one to) its operand and returns a value. If used postfix, with operator after operand (for example, x++), then it returns the value before incrementing. If used prefix with operator before operand (for example, ++x), then it returns the value after incrementing.

For example, if x is 10, then the statement y = x++ sets y to 10 and increments x to 11. If x is 10, then the statement y = ++x increments x to 11 and sets y to 11.

In ColdFusion, a simple example:

<cfset x = 10 />
<cfset y = x++ />
 
<cfdump var="#variables#" label="Increment Operator Test 1" />

The above code returns:

Increment Operator Test 1

Switching the order of the operator to be before the variable:

<cfset x = 10 />
<cfset y = ++x />
 
<cfdump var="#variables#" label="Increment Operator Test 2" />

The above code returns; note that both variables return 11:

Increment Operator Test 2

-- (Decrement)

The decrement operator is used as follows:

var-- or --var

This operator decrements (subtracts one from) its operand and returns a value. If used postfix (for example, x–), then it returns the value before decrementing. If used prefix (for example, –x), then it returns the value after decrementing.

For example, if x is three, then the statement y = x– sets y to 3 and decrements x to 2. If x is 3, then the statement y = –x decrements x to 2 and sets y to 2.

In ColdFusion, a slightly more complex example:

<cfscript>
//decrement the variable y
for(y=5; y > 0; y--)
{
	writeOutput(y);
}
//returns 54321
</cfscript>

The above code loops from 5 to 1, decrementing the value of y by 1 on each iteration. The returned output is therefore 54321.

We could now combine the increment and decrement operators to do even more complex operations. E.g.:

<cfscript>
//create a new array
arrTemp = arrayNew(1);
//create a new variable for the array counter
x = 1;
//loop y, decrement the variable y
for(y=5; y > 0; y--)
{
	arrTemp[x++] = y;
}
</cfscript>
 
<cfdump var="#arrTemp#" label="Combined Increment Decrement Operator Test" />

The above code loops from 5 to 1, decrementing the value of y by 1 on each iteration. At the same time, the value of x increments by 1 on each iteration and is used to define the array index, i.e. arrTemp[1].

The returned output can be displayed as follows:

Combined Increment Decrement Operator Test

Such code serves to demonstrate how you can set up complex operations without the need to use the following, antiquated operations:

<cfset x = incrementValue(x) />
<cfset y = y+1 />
<cfset a = decrementValue(a) />
<cfset b = b-1 />

- (Unary Negation)

The unary negation operator precedes its operand and negates it. For example, y = -x negates the value of x and assigns that to y; that is, if x were 3, y would get the value -3 and x would retain the value 3. This is not new to ColdFusion 8, but it is worth a mention.

In ColdFusion, this can be shown by the following:

<cfset x = 3 />
<cfset y = -x />
 
<cfdump var="#variables#" label="Unary Operator Test" />

The above code returns:

Unary Operator Test