Text input fields with customized automatic completion have lots of great uses. However, I've found that many of the scripts available on the Internet are hard to follow, poorly documented, or difficult to hack.
This script is an attempt at providing a solution to the problem that is clear and modular enough to be easily hacked up and modified for other uses.
Here's a quick example that was instantiated by adding javascript in-line with the form:
<input type="text" name="state" id="state"> <script language="Javascript"> var states = new Array("Alabama","Alaska","American Samoa", ... new AutoSuggest(document.getElementById('state'),states); </script>
While this is easy to demonstrate, it does tend to crap javascript all over your pretty HTML, ruining the separation of structure and behavior. I've also included an example demonstrating a cleaner way to bind the script to the input. I wouldn't recommend adding the script in-line, it just makes for an easy example.
Unfortunately, the page requires a little set-up at this point to make the script work.
You'll need to add the following to your HTML:
<div id="autosuggest"><ul></ul></div>
You'll also want to add some rules to your CSS to define the look of your dropdown:
.suggestion_list
{
background: white;
border: 1px solid;
padding: 4px;
}
.suggestion_list ul
{
padding: 0;
margin: 0;
list-style-type: none;
}
.suggestion_list a
{
text-decoration: none;
color: navy;
}
.suggestion_list .selected
{
background: navy;
color: white;
}
.suggestion_list .selected a
{
color: white;
}
#autosuggest
{
display: none;
}
There are still lots of improvements that could be made to this script:
There are plenty of other fun features that could be added. The goal for this release is to get the job done with clean, legible code that's easy to hack, so I just stuck with the basics. Go nuts, make something cool, and send it my way.
This code is available for use under the terms of the LGPL. That means you can use it however you want, even in for-fee applications. If you make any modifications to it, though, they must also be made available via the LGPL.
If you make any nifty improvements, I'd love to hear about them. Drop me a line at joekepley at yahoo·com.
This release ©2005 The Sling & Rock Design Group Inc., released via Gadgetopia.com.