One of the feature I decided early on to include in the Time-Tracker application was a type-ahead tool, akin to the famous Google Suggest. You can take a look at the old demo do get an idea of what I’m talking about.
After just a few weeks into the development of the Time-Tracker, the Type-Ahead script was ripe for refactoring. I needed a way to handle private suggestion lists as well as shared lists. I also wanted to use the same Type-Ahead object for several input fields.
The new version now runs smoothly in the Time-Tracker. Here’s how to use it in your own projects (licensed under the CC-GNU LGPL).
Source Files
Usage Notes
Add the following javascript code to your page to add the Type-Ahead behavior to any text field.
/* Wait for the page to finish loading */
XBrowserAddHandler(window,'load', function() {
/* Instanciate the TypeAhead object */
var typeAhead = new TypeAhead('listName', 'groupName');
/* Assign the TypeAhead Object to an input field */
typeAhead.initInput('inputFieldID');
} );
The listName / groupName pair identifies the list of suggestion in the database. If you omit the groupName parameter the list will be shared by everyone. If you set the groupName to something unique, like a username or userid, you’ll have a distinct list per user (or group, whatever…).
The second line binds the object to an input field. As a reference, here’s the HTML markup for the input field. Note that the value of the id attribute is the one used in the binding above.
<input type="text" id="inputFieldID" name="..." ... />
The Type-Ahead object can be binded to only one input at a time, but it can be reassigned to a different field easily and quickly, for instance when the field gets the focus:
document.getElementById('inputFieldID').onfocus = function() {
typeAhead.initInput('inputFieldID') };
document.getElementById('anotherFieldID').onfocus = function() {
typeAhead.initInput('anotherFieldID') };
Database Structure
The ‘USER’ column has been added to the SUGGESTIONS table since the last version . Here’s the SQL statement for MySQL:
CREATE TABLE `SUGGESTIONS` (
`ID` int(11) NOT NULL uto_increment,
`FIELD_ID` varchar(100) NOT NULL default '',
`VALUE` varchar(255) NOT NULL default '',
`USER` varchar(255) NOT NULL default '',
`FREQUENCY` int(11) NOT NULL default '1',
PRIMARY KEY (`ID`))
TYPE=MyISAM AUTO_INCREMENT=1 ;
You’ll need to create a database with this table and change the connection settings in the PHP file (database name, username and password).
Browsers Supported
The type-ahead functionality works with IE5.5+, Safari 1.2+, Gecko-based browsers (Firefox, Mozilla, Netscape 7+, … ) and Opera 7+(*).
Note: Comments are now closed. Please visit the discussion board if you want to discuss the subject of this post. Thank you.
Technorati Tags: Ajax, Suggest