(based on Autosuggest with Ajax v. 2.1.3 of Timothy Groves)
Here's Version 1.0.1 of my Ajax-powered auto-complete textfield. The compilation of this demo has been made using the demo resources of Timothy Groves - http://www.brandspankingnew.net
I had to do an autocomplete textfield object and looking for good resources on the net (never reinvent the wheel) I found the, very good job of Timothy Groves, Autosuggest. I had a couple of issues to resolve as the object did not fully comply with the requirements of my job. It had to be part of a framework that makes and extensive use of Prototype.js 1.5.1. and also other features such as:
Icon Notifier (Spinner between Ajax calls)
Fire onAjaxFailure events when an error occurs during Ajax calls
Be able to set a custom width
A more flexible and dynamic creation of the autocomplete text field
Autosuggest was a great job, so I redefined the object and create AutoComplete. Once created, I thought that I should share with others my work as Timothy so kindly did and here it is. Hope this could help you out with your job and saves you hours of work.
TODO
Multiple column support. Just like gmail does, when a user enters a comma or semicolon, a new list is created when inserting any character after that.
Dynamic themes. Being able to change the style of the autocomple and dropdown list could be a really nice feature to have.
(If anyone of you does it, please contact me so whether I can post it on my blog or have a link to your project)
Disclaimer
I do not want to take any credit for the creation of the following demos. I have reused completely the work of Timothy, he should be the one granted with that.
Examples & description
Example (JSON)
Description
The AutoComplete 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, ASP, ASPX 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 AutoComplete instance. It is called when the user selects an entry, and writes the full entry info into an span object.
Example (XML)
Usage
The script requires prototype.js and a single javascript file to be included in the HEAD:
autocomplete.js
A normal text field is transformed into an AutoComplete text field dynamically by using the following code (placed anywhere you want -in the examples above they are created on the onfocus textfield event):
var options = {
script:'test.php?json=true&limit=6&',
varname:'input',
json:true,
shownoresults:true,
maxresults:16,
callback: function (obj) { $('json_info').update('you have selected: '+obj.id + ' ' + obj.value + ' (' + obj.info + ')'); }
};
var json=new AutoComplete('test_json',options);
The options object contains the options for the AutoComplete 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 (to use POST method, you will need to modify the AJAX (-doAjaxRequest function) request and also the , 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:
script: function (input) { return "test.php?input="+input+"&testid="+document.getElementById('testid').value; }
This allows you to build the script URL dynamically, passing variable data from somewhere else in your document (eg. from another field, as in the example above). If the script returns false, no AJAX request will be made.
The XML output from the script should have the following structure (you can modify this and its client handle via the setSuggestions function of the AutoComplete object:
The list can then be styled using normal CSS. Check out the CSS file.
Options
The options object can contain the following properties:
Property
Type
Default
Description
script
String / Function
-
REQUIRED! Either: A string containing the path to the script that returns the results in XML format. (eg, "myscript.php?")
Or: A function that accepts on attribute, the autosuggest field input as a string, and returns the path to the result script.
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
"autocomplete"
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
{id:"1", value:"Foobar", info:"Cheshire"}
json
Boolean
false
Whether or not a results are returned in JSON format. If not, script assumes results are in XML.
maxentries
Integer
25
The maximum number of entries being returned by the script. (Should correspond to the LIMIT clause in the SQL query.)
onAjaxError
function
null
If an Ajax request fails, this function will be called (if any). NOTE: a parameter (HTTP_STATUS) will be passed to the function, so you can display your own custom error message.
onAjaxRequest:function(status){alert(status);}
setWidth
Boolean
false
If set to true, the dropdown list will be within the boundaries of minWidth and maxWidth options.
minWidth
Integer
100
If setWidth is equal to true, then the dropdown list will be a minimum width of whatever this option specifies
maxWidth
Integer
200
If setWidth is equal to true, then the dropdown list will be a maximum width of whatever this option specifies
useNotifier
Boolean
true
true by default, this option will display icons to notify that is an autocomplete textfield and also a spinner when an AJAX call is being made to the server.
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 AutoComplete list, the timeout is cancelled altogether, until the mouse pointer is moved off the list.