↑
Main Page
guts
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) {
arrResult.push(arrValues[i]);
}
}
}
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
for
loop is used to check each value to see if it begins
with the string. To determine this, the
indexOf()
method is used. When
indexOf()
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
TextUtil.autosuggest()
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
arrValues
, the call looks like this:
<input type=”text”
onkeyup=”TextUtil.autosuggest(this, arrValues, ‘lstSuggestions’)” />
The
onkeyup
event handler is used because the
keyup
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);
ListUtil.clear(oListbox);
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
sListboxId
. The list box is then
cleared of all prior options by using the
ListUtil.clear()
method explained earlier in the chapter.
363
Forms and Data Integrity
14_579088 ch11.qxd 3/28/05 11:40 AM Page 363
Free JavaScript Editor
Ajax Editor
©
→