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 jQuery
- A server-side script that can respond to the AJAX request, in our case ColdFusion
The demo will specifically look at a simple form text input field, which takes a country name.
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.
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).
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>
Where To Take It Next
The above example only shows a simple text list, separated by carriage returns. It is more preferable to use JSON.
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.