Main Page

colors called

Next, the method calls
TextUtil.autosuggestMatch()
to get the matching values for the string in the
text box. The last step is to iterate through the matching values and add them to the list box by using the
ListUtil.add()
method.
To use this method, you must set up a text box and list box on a page along with an array of values to
use. The values should be in alphabetical order so that they appear in alphabetical order when sug-
gested to the user. Here’s an example page:
<html>
<head>
<title>Autosuggest Textbox Example</title>
<script type=”text/javascript” src=”listutil.js”></script>
<script type=”text/javascript” src=”textutil.js”></script>
<script type=”text/javascript”>
var arrColors = [“red”, “orange”, “yellow”, “green”, “blue”, “indigo”,
“violet”, “brown”, “black”, “tan”, “ivory”, “navy”,
“aqua”, “white”, “purple”, “pink”, “gray”, “silver”];
arrColors.sort();
function setText(oListbox, sTextboxId) {
var oTextbox = document.getElementById(sTextboxId);
if (oListbox.selectedIndex > -1) {
oTextbox.value =
oListbox.options[oListbox.selectedIndex].text;
}
}
</script>
</head>
<body>
<p>Type in a color in lowercase:<br />
<input type=”text” value=”” id=”txtColor”
onkeyup=”TextUtil.autosuggest(this, arrColors, ‘lstColors’)” /><br />
<select id=”lstColors” size=”5” style=”width: 200px”
onclick=”setText(this, ‘txtColor’)”></select>
</p>
</body>
</html>
In this example, an array of colors called
arrColors
is defined. Because the values aren’t in alphabetical
order, the
sort()
method is called after the array is created. It is this array that is referenced by
TextUtil.autosuggest()
. The list box with the ID
“lstColors”
contains the suggestions for what
the user may want to type. This list box also has an
onclick
event handler that simply sets the text box
value to the currently selected option (this is for convenience, although it isn’t a necessary part of the
autosuggest functionality). The
setText()
method takes two arguments: the list box and the ID of the
text box. The method then gets a reference to the text box and sets its value to the currently selected
value in the list box.
364
Chapter 11
14_579088 ch11.qxd 3/28/05 11:40 AM Page 364


JavaScript EditorFree JavaScript Editor     Ajax Editor


©