Hack 78. Create an Auto-Complete Field


Give the user helpful suggestions by changing the contents of a text box as they type.

Web surfers can always use a little help. Google took advantage of this fact when it created Google Suggest (http://www.google.com/webhp?complete= 1&hl=en), a simple Ajax variation on its massively popular search page. When the user types in a search term, Google Suggest displays a list of search suggestions beneath the text box. What many people don't notice is that the text in the text box is also alteredthe top entry from the list is automatically entered. Figure 9-12 shows this behavior in action: I've only typed the letters "javas" into the text box, but Google Suggest has added the end of the word, "cript," for me.

Figure 9-12. Google makes suggestions


This hack will show how to modify text in a text box as the user types, using suggestions received from the web server.

Of course, the list of possible suggestions depends entirely on the needs of your application. "Create an Auto-Complete Field with script.aculo.us" [Hack #65] discussed how to implement an auto-completion field for email addresses (using script.aculo.us effects). For this hack, I wrote a tiny server script that scans a list of dictionary words on the server and returns the first match.

Many Linux and Unix servers have a text file called words that contains a list of words (one per line) used by spelling and password checkers. It's usually located at /usr/dict/words or /usr/share/dict/words.


My little server receives a single parameter, var. This contains the letters the user has typed thus far. The server finds a match and sends back the remaining portion of the word. So, like in the previous Google example, if I type in "javas" and the server matches on the word "javascript," it sends back the remaining part of the word: "cript."

To make things easy on the client side, we'll have a single function, autocomplete( ), that's hooked into a text box's onKeyup event. It gets called every time the user presses a key:

<input type="text"         id="txtAuto" name="txtAuto"         onkeyup="autocomplete (this,event);"  />

The autocomplete( ) function, shown in the upcoming code sample, first checks that the most recent keystroke is an alphanumeric character. It thensends the current value of the text box to the server. The server responds with the remaining portion of the matching word:

var url = "/cgi-bin/autocomplete/suggest.cgi?"; function autocomplete (sender, ev) {     //Only process alphanumeric keystrokes     if (( ev.keyCode >= 48 && ev.keyCode <= 57 )              ||  ( ev.keyCode >= 65 && ev.keyCode <= 90 )) {         //Prepare a server request         var httpreq = getHTTPObject(  );         var parms = "val=" + sender.value;         httpreq.open("GET", url + parms, true);         //Response function         httpreq.onreadystatechange = function (  ) {             if (httpreq.readyState == 4) {                 var suggestion = httpreq.responseText;                 var txtAuto = document.getElementById ('txtAuto');                        if ((suggestion) && (txtAuto.value == original_text)) {                     //Firefox and Opera                     if (document.getSelection) {                         var initial_len = txtAuto.value.length;                         txtAuto.value += suggestion;                         txtAuto.selectionStart = initial_len;                         txtAuto.selectionEnd = txtAuto.value.length;                      }                     //Internet Explorer                     else if (document.selection) {                         var sel = document.selection.createRange (  );                         sel.text = suggestion;                                     sel.move ("character", -suggestion.length);                          sel.findText (suggestion);                         sel.select (  );                     }                 }             }         }         httpreq.send (null);     } }

At this point, we need to work around the quirks of different browsers. Microsoft's Internet Explorer uses different methods for handling text selected in a listbox than browsers such as Firefox and Opera. The goal is the same in all browsers: we need to graft the end of the word (grabbed from the server) onto the beginning of the word (that the user typed). But we also must select that new text.

Why? A user who is typing and not paying close attention to what's on the screen may not notice that we just added several characters to the text. That's bad, especially if our suggestion is wrong. By selecting (highlighting) the text we've added, we allow the user to obliterate our suggestion on the next keystroke. For example, say the user wants to type "intense." After the user has entered the first three letters, the program suggests the word "intact" in Figure 9-13.

Figure 9-13. A not quite intact word


But the last half of the word, "act" is selected, so when the user enters the next letter, "e," that letter replaces the selected text. The server now sends back a match for the first four letters, "inte," as shown in Figure 9-14.

Figure 9-14. Auto-selection in action


If this still isn't quite what the user wants, she can continue to type without worrying that the program will capriciously alter the entered text.

Hacking the Hack

This hack works best if the server can keep up with the user's typing. Make sure your server script is as fast as possible. You may get better performance by sending several potential matches to the server and caching the ones you don't yet need. When the user enters "a," for example, you can retrieve all the words that start with "a" and store them in a JavaScript array. Then, when the user types the next letter, you'll already have those matches ready.

Mark Pruett




Ajax Hacks
Ajax Hacks: Tips & Tools for Creating Responsive Web Sites
ISBN: 0596101694
EAN: 2147483647
Year: 2006
Pages: 138

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net