↑
Main Page
Creating an Autosuggest Text Box
Start with the
shiftUp()
method, which moves an option up one spot in the list box:
ListUtil.shiftUp = function (oListbox, iIndex) {
if (iIndex > 0) {
var oOption = oListbox.options[iIndex];
var oPrevOption = oListbox.options[iIndex-1];
oListbox.insertBefore(oOption, oPrevOption);
}
};
This method first checks to make sure the index of the option to move is greater than 0 because, of course,
you cannot move the first option up one spot. The option with the given index is stored in the variable
oOption
and the option before it is stored in
oPrevOption
. Last, the
insertBefore()
method is called
to move
oOption
before
oPrevOption
. The method to move an option down one spot is very similar:
ListUtil.shiftDown = function (oListbox, iIndex) {
if (iIndex < oListbox.options.length - 1) {
var oOption = oListbox.options[iIndex];
var oNextOption = oListbox.options[iIndex+1];
oListbox.insertBefore(oNextOption, oOption);
}
};
In this case, you must first get the collection of options in order to make sure that
iIndex
isn’t the last posi-
tion in the list (because you can’t move the last option down any further). The option in position
iIndex
is
stored in
oOption
; the option in the next position is stored in
oNextOption
. Using
insertBefore()
,
oNextOption
is placed before
oOption
in the list box.
These two methods can be used as in the following example:
var oListbox = document.getElementById(“selListbox”);
ListUtil.shiftUp(oListbox,1); //move the option in position 1 up one spot
ListUtil.shiftDown(oListbox,2); //move the option in position 2 down one spot
Creating an Autosuggest Text Box
Let’s face it, people really don’t enjoy filling out forms, especially when values need to be typed in.
That’s why applications like Microsoft Outlook incorporate autosuggest text boxes, which are text boxes
that examine the first few characters a user has typed and then suggests a word (or multiple words)
from a given list that may complete his entry. Web browsers also work in this way when you are typing
a Web address. With a little bit of JavaScript trickery, it’s possible to create the same type of behavior in
Web forms.
Matching
The first step in the process is to write a method to search an array of strings and return all values that
begin with a certain set of letters (for example, if you pass in
a
, the method returns all values in the array
beginning with the letter
a
). This method is called
TextUtil.autosuggestMatch()
and takes two
arguments: the text to match and the array of values to match against.
362
Chapter 11
14_579088 ch11.qxd 3/28/05 11:40 AM Page 362
Free JavaScript Editor
Ajax Editor
©
→