javascript创建自动提示文本框(js笔记)

由于很多人不愿意手工填写表单,觉得这样很麻烦,所以创建自动提示的文本框是非常有必要的。

该文本框在用户输入时会检测输入的头几个字符,然后给出一个可帮助用户输入的单词列表,这样会给用户带来很多方便。

<!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>

效果如下:



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值