Main Page


TextUtil.autosuggestMatch = function (sText, arrValues) {
var arrResult = new Array;
if (sText != “”) {
for (var i=0; i < arrValues.length; i++) {
if (arrValues[i].indexOf(sText) == 0) {
return arrResult;
The first step in this method is to create an array to return all matching values. Next, the method checks
to ensure that the string to match isn’t empty (an empty string is always considered to be present in
any string). If the string isn’t empty, a simple
loop is used to check each value to see if it begins
with the string. To determine this, the
method is used. When
returns 0, it means
that the string is present at the beginning of the value, so it should be added to the result array. Finally,
the array of matching values is returned.
The guts
With the matching method complete, it’s time to create the most important part of the script: the
method. This method takes three arguments: the text box to act on, an array
of possible values, and the ID of a list box in which the suggestions should be displayed. Assuming that
the array of values is called
, the call looks like this:
<input type=”text”
onkeyup=”TextUtil.autosuggest(this, arrValues, ‘lstSuggestions’)” />
event handler is used because the
event fires after a character has been entered into
the text box, allowing the suggestions to be made on the most recent change to the text box. The method
is defined as follows:
TextUtil.autosuggest = function (oTextbox, arrValues, sListboxId) {
var oListbox = document.getElementById(sListboxId);
var arrMatches = TextUtil.autosuggestMatch(oTextbox.value, arrValues);
for (var i=0; i < arrMatches.length; i++) {
ListUtil.add(oListbox, arrMatches[i]);
This method begins by getting a reference to the list box with the ID of
. The list box is then
cleared of all prior options by using the
method explained earlier in the chapter.
Forms and Data Integrity
14_579088 ch11.qxd 3/28/05 11:40 AM Page 363

JavaScript EditorFree JavaScript Editor     Ajax Editor