Friday, August 15, 2008

Autocomplete Form Fields (with jQuery)

I recently added a feature to Ringlight which lets you share a private file with a particular user. There is a field to enter the username that you want to share with and obviously this field needs to autocomplete as you type. This is a feature that users expect now and so it's not really optional.

jQuery makes it very easy to add this feature:
  1. Download the autocomplete extension for jQuery. You'll need both the javascript and CSS files.
  2. Add an input field to your form:
  3. Set the cacheLength option to speed up responsiveness: options={cacheLength: "20"};
  4. Call the autocomplete extension: $("#youAutocompleteMe").autocomplete(url, options);
  5. You'll need a server-side script installed at the url you pass to autocomplete to return matches.
The autocomplete function will call the given url, passing the text currently in the input box in the q parameter. Your server-side code should return a newline-delimited list of matches.

That's it! It's pretty easy. The key to performance is setting that cacheLength parameter as it default to 1, which doesn't provide much caching at all.