Home » Tutorials Advanced Tutorial

Creating an Autosuggest Textbox with JavaScript, Part 1 - Page 2

2.2/5.0 (29 votes total)
Rate:

Nicholas C. Zakas
February 10, 2006


Nicholas C. Zakas
Nicholas C. Zakas is a professional Web designer who specializes in user interface design for Web applications using JavaScript, Dynamic HTML, CSS, XML, and XSLT.


http://www.nczonline.net
Nicholas C. Zakas has written 12 tutorials for JavaScriptSearch.
View all tutorials by Nicholas C. Zakas...

Implementing Type Ahead

Now that you can select only specific parts of the textbox, it's time to implement the type ahead functionality. The method defined here accepts a suggestion and assumes that it is appropriate given the contents of the textbox. The steps involved are:

  1. Get the length of the text already in the textbox.
  2. Place the suggestion into the textbox.
  3. Select only the portion of the text that the user didn't type using the information from step 1.

Additionally, since type ahead can only be supported in Internet Explorer and Mozilla, you should check to make sure one of those browsers is being used. If the browser doesn't support text selection, only the first two steps will be executed; which would disturb the user's typing. The solution is to skip the type ahead feature if it's not supported. Once again, testing for the createTextRange() and setSelectionRange() methods of the textbox is the way to go:

AutoSuggestControl.prototype.typeAhead = function (sSuggestion) {
    if (this.textbox.createTextRange || this.textbox.setSelectionRange) {
        var iLen = this.textbox.value.length;
        this.textbox.value = sSuggestion;
        this.selectRange(iLen, sSuggestion.length);
    }
};

But where does the suggestion come from? This is where the autosuggest() method comes in.

The autosuggest() Method

Perhaps the most important method in the control is autosuggest(). This single method is responsible for receiving an array of suggestions for the textbox and then deciding what to do with them. Eventually, this method will be used to implement the full autosuggest functionality (including dropdown suggestions), but for now, it's used to implement type ahead only.

Since autosuggest() will be passed an array of suggestions, you have your pick as to which one to use for the type ahead value. It's recommended to always use the first value in the array to keep it simple. The problem is that there may not always be suggestions for a value, in which case an empty array will be passed. To provide for this, you must first check to see if there are any items in the array; if there are, call the typeAhead() method and pass in the first suggestion, like this:

AutoSuggestControl.prototype.autosuggest = function (aSuggestions) {

    if (aSuggestions.length > 0) {
        this.typeAhead(aSuggestions[0]);
    }
};

You may be wondering at this point where the suggestions will come from. It's the job of a suggestion provider to pass in the array of suggestions to this method. This will be discussed further when the sample suggestion provider is created later on in the article. But first, you need to know how to interact with the user as he/she is typing.

Handling Key Events

Of course, the autosuggest functionality has to be tied in to the textbox using events. There are three events that deal with keys: keydown, keypress, and keyup. The keydown event fires whenever the user presses a key on the keyboard but before any changes occur to the textbox. This obviously won't help with autosuggest because you need to know the full text of the textbox; using this event would mean being one keystroke behind. For the same reason, the keypress event can't be used. It is similar to keydown, but fires only when a character key is pressed. The keyup event, however, fires after changes have been made to the textbox, which is exactly when autosuggest should begin working.

Setting up an event handler for the textbox involves two steps: defining a function and assigning it as an event handler. The function is actually a method of the autosuggest control called handleKeyUp(). This method expects the event object to be passed in as an argument (how to accomplish this is discussed later) so that it can tell whether the key being pressed should enact the autosuggest functionality. Since keyup fires for all keys, not just character keys, you'll receive events when someone uses a cursor key, the tab key and any other key on the keyboard. To avoid interfering with how a textbox works, suggestions should only be made when a character key is pressed. This is where the event object's keyCode property enters the picture.

The keyCode property is supported by most modern browsers (including Internet Explorer on Windows and Macintosh, Mozilla, Opera, and Safari) and returns a numeric code representing the key that was pressed. Using this property, it's possible to set up behaviors for specific keys. Since the autosuggest functionality should happen only when character keys are pressed, many think that you need to specify all of the character key codes. It's actually best to take the opposite approach and specify all of the non-character key codes to be ignored. This approach is more efficient because there are more character keys than non-character keys.

So which keys need to be ignored? Here's the complete list and their key codes:

KeyCodeKeyCode
Backspace8Print Screen44
Tab9Delete46
Enter13F1112
Shift16F2113
Ctrl17F3114
Alt18F4115
Pause/Break19F5116
Caps Lock20F6117
Esc27F7118
Page Up33F8119
Page Down34F9120
End35F10121
Home36F11122
Left Arrow37F12123
Up Arrow38  
Right Arrow39  
Down Arrow40  

You may notice a pattern among the key codes. It looks like all keys with a code less than or equal to 46 should be ignored and all keys with codes between 112 and 123 should be ignored. This is generally true, but there is an exception. The space bar has a key code of 32, so you actually need to check to see if the code is less than 32, between 33 and 46, or between 112 and 123. If it's not in any one of these groups, then you know it's character.

Next page


Add commentAdd comment (Comments: 0)  

Advertisement

Partners

Related Resources

Other Resources

arrow