由于很多人不愿意手工填写表单,觉得这样很麻烦,所以创建自动提示的文本框是非常有必要的。
该文本框在用户输入时会检测输入的头几个字符,然后给出一个可帮助用户输入的单词列表,这样会给用户带来很多方便。
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title> 自动提示文本 </title> <script language="javascript"> <!-- var ListObj = new Object(); //创建匹配数组 var arrColors = ["red" , "orange" , "yellow" , "green" , "blue" , "indigo" , "violet" , "brown" , "black" , "tan" , "ivory" , "navy" , "aqua"]; arrColors.sort(); //对数组进行排序,默认按升序排序 //添加选项 ListObj.add = function (oListbox , sName , sValue){ var oOption = document.createElement("option"); oOption.appendChild(document.createTextNode(sName)); if (arguments.length == 3){ oOption.setAttribute("value",sValue); }//添加选项 oListbox.appendChild(oOption); } //移动选项 ListObj.remove = function (oListbox , iIndex){ oListbox.remove(iIndex); } //清空选项 ListObj.clear = function (oListbox){ for(var i=oListbox.options.length-1;i>=0;i--){ ListObj.remove(oListbox,i); } } var Textobj = new Object(); //创建与数组匹配的方法 Textobj.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]); //将颜色数组放入arrResult } } } return arrResult; } //实现搜索,并将结果数组添加到列表框中 Textobj.autosuggest = function(oTextbox , arrValues , sListboxId){ //获取列表索引 var oListbox = document.getElementById(sListboxId); //将匹配的颜色放入文本框内 var arrMatches = Textobj.autosuggestMatch(oTextbox.value , arrValues); //清空选项 ListObj.clear(oListbox); for (var i=0;i<arrMatches.length ;i++ ){ ListObj.add(oListbox , arrMatches[i]); } } //将列表框中的选项添加到文本框中 function setText (oListbox , sTextboxId){ var oTextbox = document.getElementById(sTextboxId); if (oListbox.selectedIndex >-1){ oTextbox.value = oListbox.options[oListbox.selectedIndex].text ; } } --> </script> </head> <body> <p>输入你喜欢的颜色:<br/> <input type="text" value="" id="txtColor" οnkeyup="Textobj.autosuggest(this, arrColors, 'lstColors')"/><br/> <select id="lstColors" size="5" style="width:200px" οnclick="setText(this,'txtColor')"></select> </p> </body> </html>
效果如下: