Copy codeThe Code is as follows:
<SCRIPT language = JScript type = text/javascript>
Var isOpera = navigator. userAgent. indexOf ("Opera")>-1;
Var isIE = navigator. userAgent. indexOf ("MSIE")> 1 &&! IsOpera;
Var isMoz = navigator. userAgent. indexOf ("Mozilla/5.") = 0 &&! IsOpera;
Function textboxSelect (oTextbox, iStart, iEnd ){
Switch (arguments. length ){
Case 1:
OTextbox. select ();
Break;
Case 2:
IEnd = oTextbox. value. length;
/* Falls through */
Case 3:
If (isIE ){
Var oRange = oTextbox. createTextRange ();
ORange. moveStart ("character", iStart );
ORange. moveEnd ("character",-oTextbox. value. length + iEnd );
ORange. select ();
} Else if (isMoz ){
OTextbox. setSelectionRange (iStart, iEnd );
}
}
OTextbox. focus ();
}
/*
Function textboxReplaceSelect (oTextbox, sText ){
If (isIE ){
Var oRange = oTextbox. createTextRange ();
ORange. text = sText;
ORange. collapse (true );
ORange. select ();
} Else if (isMoz ){
Var iStart = oTextbox. selectionStart;
OTextbox. value = oTextbox. value. substring (0, iStart) + sText + oTextbox. value. substring (oTextbox. selectionEnd, oTextbox. value. length );
OTextbox. setSelectionRange (iStart + sText. length, iStart + sText. length );
}
OTextbox. focus ();
}
*/
Function autocompleteMatch (sText, arrValues ){
For (var I = 0; I <arrValues. length; I ++ ){
If (arrValues [I]. indexOf (sText) = 0 ){
Return arrValues [I];
}
}
Return null;
}
Function autocomplete (oTextbox, oEvent, arrValues ){
Switch (oEvent. keyCode ){
Case 38: // up arrow
Case 40: // down arrow
Case 37: // left arrow
Case 39: // right arrow
Case 33: // page up
Case 34: // page down
Case 36: // home
Case 35: // end
Case 13: // enter
Case 9: // tab
Case 27: // esc
Case 16: // shift
Case 17: // ctrl
Case 18: // alt
Case 20: // caps lock
Case 8: // backspace
Case 46: // delete
Return true;
Break;
Default:
// This line below is of little use (commented out)
// TextboxReplaceSelect (oTextbox, isIE? OTextbox. value/* oEvent. keyCode */: oEvent. charCode );
Var iLen = oTextbox. value. length;
Var sMatch = autocompleteMatch (oTextbox. value, arrValues );
If (sMatch! = Null ){
OTextbox. value = sMatch;
TextboxSelect (oTextbox, iLen, oTextbox. value. length );
}
Return false;
}
}
</SCRIPT>
<SCRIPT>
Var arrValues = ["red", "orange", "yellow", "green", "blue", "indigo", "violet", "brown"];
</SCRIPT>
<H2> Autocomplete Textbox Example </H2>
<P> Type in a color in lowercase: enter a color that begins with a lowercase letter (for example, r or B) <BR> <INPUT id = txt1 onkeyup = "return autocomplete (this, event, arrValues)"> </P>