Autocomplete list box

Often you will choose an item from an HTML dropdown list box by clicking on its arrow and choosing an item from the list that appears. Sometimes, however, it can be more convenient to use the keyboard to select an item from the list.

With the standard list box, you can type a letter repeatedly to loop through all the items in the list that start with that letter. For a list box with a small number of items this does not present much of a problem, but if you have a large list it can become tedious quite fast.

Consider a dropdown list containing state names, such as the following:

Suppose you want to choose Montana from the list. You would need to press the M key 8 times to reach Montana. If you only had to do this once you might not find it too cumbersome, but suppose you were entering customer records into a new database and had many customers from Montana. This would become tiring quite quickly.

An easier solution would be to be able to type the name that you wanted and have it automatically become selected, similar to a Windows combo box. An example is the Address combo box (or the Location combo box in Netscape). As you type a URL in the box, Internet Explorer will automatically display suggestions for you based on URLs you have visited recently.

The pseudo-autocomplete list box that I have developed simulates this functionality. To see how this works, choose the button below; this will set the focus on the autocomplete list box. Then start typing a state name (Montana, for example). You will see a pop-up appear to let you know what you have already typed. When a match is encountered, the matching item will automatically become selected.

Notice that when you start typing in the box, the other list box disappears. This is a workaround for a layout "bug" in IE wherein list boxes float over anything else on a page. To prevent the possibility of the pop-up being obscured by a nearby list box, the back-end script temporarily hides any other list box on the page.

The script responds to all of the letter and number keys, as well as the ESCAPE, BACKSPACE, ENTER, and TAB keys.

The script also attempts to detect whether the user might be trying to treat the list box like a standard list box. Set the focus on the list box and then press the M key repeatedly. After 3 times, you should see an alert message appear that explains the functionality of the autocomplete list box.

As you are typing, notice that the pop-up disappears (after a short delay) if you quit typing. If you start typing again, the pop-up starts from scratch.

Finally, note that the pop-up will appear either above or below the list box, depending on how much screen real-estate you have above the list box. Go ahead and scroll the page so that the list box is at the top of the window, then start typing in the list box. The pop-up will appear below the list box.