view the original article at BrandSpankingNew
Autosuggest / Autocomplete with Ajax v. 2.0
Here's Version 2 of my Ajax-powered auto-suggestion, or auto-complete textfield.
What's new?
- Optional JSON Support
- Callback function support (set ID when user selects list item, or anything else...)
- Display extra information (see XML example below)
- Am optional message can be displayed when no results are returned
- Completes field when enter key is pressed
- Slick new look (2.0 ready!) inspired by Inquisitor
- Matching input is highlighted in the list
- Fade effect!
- Available as a single, bundled JS file
- More feature, less bug
- CSS provided in an external folder, for easy tinkering
Example (JSON)
Description
The AutoSuggest class adds a pulldown menu of suggested values to a text field. The user can either click directly on a suggestion to enter it into the field, or navigate the list using the up and down arrow keys, selecting a value using the enter key. The values for the suggestion list are to provided as XML, or as JSON (by a PHP script, or similar).
The results of the first request are cached on the client machine and are filtered as the user continues to type, to reduce the number of requests hitting the server.
In the JSON example above a callback function is passed to the autoSuggest instance. It is called when the user selects an entry, and inserts the entry id into a hidden field (visible for this example).
In the XML example below supplementary information is being displayed along with the names, in this case an english county.
Example (XML)
Usage
The script requires a single javascript file to be included in the HEAD:
bsn.AutoSuggest_c_2.0.js
A normal text field is transformed into an AutoSuggest text field by adding the following javascript to your code, either in a body.onload
function or just before the </body>
tag.
var options = {
script: "pathToScript.php?",
varname: "variableName",
json: true
};
var as = new AutoSuggest('idOfTextfield', options);
The options
object contains the (surprise, surprise) the options for the AutoSuggest instance. Note that the script variable includes the question mark (?
) at the end. This is to allow other variables to be passed to the script via GET
, for example script: "http://www.yourserver.com/backend.php?list=countries&"
. The varname
option is the name of the variable that should contain the current value of the text field, and is simpy added on to the end of the script variable when the script is called, along with the current value of the text field, giving:
http://www.yourserver.com/backend.php?list=countries&variableName=currentValue
The XML output from the script should have the following structure:
<results>
<rs id="1" info="">Foobar</rs>
<rs id="2" info="">Foobarfly</rs>
<rs id="3" info="">Foobarnacle</rs>
</results>
A JSON object should have the following structure:
{ results: [
{ id: "1", value: "Foobar", info: "Cheshire" },
{ id: "2", value: "Foobarfly", info: "Shropshire" },
{ id: "3", value: "Foobarnacle", info: "Essex" }
] }
The AutoSuggest object creates the following XHTML code, inserting as the last element in the body
:
<div style="left: 347px; top: 1024px; width: 400px;" class="autosuggest" id="as_testinput_xml">
<div class="as_header">
<div class="as_corner"></div>
<div class="as_bar"></div>
</div>
<ul id="as_ul">
<li>
<a name="1" href="#">
<span class="tl"> </span>
<span class="tr"> </span>
<span><em>W</em>aldron, Ashley<br><small>Leicestershire</small></span>
</a>
</li>
<li>
<a name="2" href="#">
<span class="tl"> </span>
<span class="tr"> </span>
<span><em>W</em>heeler, Bysshe<br><small>Lincolnshire</small></span>
</a>
</li>
</ul>
<div class="as_footer">
<div class="as_corner"></div>
<div class="as_bar"></div>
</div>
</div>
The list can then be styled using normal CSS. Check out the CSS file.
NOTE: Safari seems to require that the position
attribute of the body
element be set to relative
.
Options
The options object can contain the following properties:
Property | Type | Default | Description |
---|---|---|---|
script | String | - | REQUIRED! The path to the script that returns the results in XML format. |
varname | String | "input" | Name of variable passed to script holding current input. |
minchars | Integer | 1 | Length of input required before AutoSuggest is triggered. |
className | String | "autosuggest" | Value of the class name attribute added to the generated ul . |
delay | Integer | 500 | Number of milliseconds before an AutoSuggest AJAX request is fired. |
timeout | Integer | 2500 | Number of milliseconds before an AutoSuggest list closes itself. |
cache | Boolean | true | Whether or not a results list should be cached during typing. |
offsety | Integer | -5 | Vertical pixel offset from the text field. |
shownoresults | Boolean | true | Whether to display a message when no results are returned. |
noresults | String | No results! | No results message. |
callback | Function |
A function taking one argument: an object
|
|
json | Boolean | false | Whether or not a results are returned in JSON format. If not, script assumes results are in XML. |
Timeouts
The default timeout is set at 2500 milliseconds. After two and a half seconds of inactivity the list closes itself. However, this timeout is reset each time the user types another character. Furthermore, if the user moves the mouse pointer over the AutoSuggest list, the timeout is cancelled altogether, until the mouse pointer is moved off the list.
AJAX Errors
At the moment, AJAX errors simply trigger a javascript alert()
containing the error code.