JavaScript实现带自动提示的文本框效果代码

示例一:直接编写AJAX 实现。
客户端:


代码如下:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>Ajax实现自动提示的文本框</title>
<style>
<!--
body{
font-family:Arial, Helvetica, sans-serif;
font-size:12px; padding:0px; margin:5px;
}
form{padding:0px; margin:0px;}
input{
/* 用户输入框的样式 */
font-family:Arial, Helvetica, sans-serif;
font-size:12px; border:1px solid #000000;
width:200px; padding:1px; margin:0px;
}
#popup{
/* 提示框div块的样式 */
position:absolute; width:202px;
color:#004a7e; font-size:12px;
font-family:Arial, Helvetica, sans-serif;
left:41px; top:25px;
}
#popup.show{
/* 显示提示框的边框 */
border:1px solid #004a7e;
}
#popup.hide{
/* 隐藏提示框的边框 */
border:none;
}
/* 提示框的样式风格 */
ul{
list-style:none;
margin:0px; padding:0px;
}
li.mouseOver{
background-color:#004a7e;
color:#FFFFFF;
}
li.mouseOut{
background-color:#FFFFFF;
color:#004a7e;
}
-->
</style>
<script language="javascript">
var oInputField; //考虑到很多函数中都要使用
var oPopDiv; //因此采用全局变量的形式
var oColorsUl;
var xmlHttp;
function createXMLHttpRequest(){
if(window.ActiveXObject)
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
else if(window.XMLHttpRequest)
xmlHttp = new XMLHttpRequest();
}
function initVars(){
//初始化变量
oInputField = document.forms["myForm1"].colors;
oPopDiv = document.getElementById("popup");
oColorsUl = document.getElementById("colors_ul");
}
function clearColors(){
//清除提示内容
for(var i=oColorsUl.childNodes.length-1;i>=0;i--)
oColorsUl.removeChild(oColorsUl.childNodes[i]);
oPopDiv.className = "hide";
}
function setColors(the_colors){
//显示提示框,传入的参数即为匹配出来的结果组成的数组
clearColors(); //每输入一个字母就先清除原先的提示,再继续
oPopDiv.className = "show";
var oLi;
for(var i=0;i<the_colors.length;i++){
//将匹配的提示结果逐一显示给用户
oLi = document.createElement("li");
oColorsUl.appendChild(oLi);
oLi.appendChild(document.createTextNode(the_colors[i]));
oLi.onmouseover = function(){
this.className = "mouseOver"; //鼠标经过时高亮
}
oLi.onmouseout = function(){
this.className = "mouseOut"; //离开时恢复原样
}
oLi.onclick = function(){
//用户点击某个匹配项时,设置输入框为该项的值
oInputField.value = this.firstChild.nodeValue;
clearColors(); //同时清除提示框
}
}
}
function findColors(){
initVars(); //初始化变量
if(oInputField.value.length > 0){
createXMLHttpRequest(); //将用户输入发送给服务器
var sUrl = "9-10.aspx?sColor=" + oInputField.value + "&timestamp=" + new Date().getTime();
xmlHttp.open("GET",sUrl,true);
xmlHttp.onreadystatechange = function(){
if(xmlHttp.readyState == 4 && xmlHttp.status == 200){
var aResult = new Array();
if(xmlHttp.responseText.length){
aResult = xmlHttp.responseText.split(",");
setColors(aResult); //显示服务器结果
}
else
clearColors();
}
}
xmlHttp.send(null);
}
else
clearColors(); //无输入时清除提示框(例如用户按del键)
}
</script>
</head>
<body>
<form method="post" name="myForm1">
Color: <input type="text" name="colors" id="colors" onkeyup="findColors();" />
</form>
<div id="popup">
<ul id="colors_ul"></ul>
</div>
</body>
</html>

服务器端(9-10.aspx ):


代码如下:

<%@ Page Language="C#" ContentType="text/html" ResponseEncoding="gb2312" %>
<%@ Import Namespace="System.Data" %>
<%
Response.CacheControl = "no-cache";
Response.AddHeader("Pragma","no-cache");
string sInput = Request["sColor"].Trim();
if(sInput.Length == 0)
return;
string sResult = "";
string[] aColors = new string[]{"aliceblue","antiquewith","aquamarine","azure","beige","bisque","black","blanchedalmond","blue","blueviolet","brass","bronze","brown","burlywood","cadetblue","chartreuse","chocolate","copper","coral","cornfloewrblue","cornsilk","cyan","darkblue","darkcyan","darkgoldenrod","darkgray","darkgreen","darkhaki","darkmagenta","darkolivegreen","darkorchid","darkorenge","darkred","darksalmon","darkseagreen","darkslateblue","darkslategray","darkturquoise","darkviolet","deeppink","deepskyblue","dimgray","dodgerblue","feldspar","firebrick","floralwhite","forestgreen","fuchsia","gainsboro","gold","goldenrod","golenrod","gostwhite","gray","green","greenyellow","honeydew","hotpink","indianred","inen","ivory","khaki","lavender","lavenderblush","lawngreen","lemonchiffon","lightblue","lightcoral","lightcyan","lightgodenrod","lightgodenrodyellow","lightgray","lightgreen","lightpink","lightsalmon","lightseagreen","lightskyblue","lightslateblue","lightslategray","lightsteelblue","lightyellow","lime","limegreen","magenta","magenta","maroom","maroon","mediumaquamarine","mediumblue","mediumorchid","mediumpurpul","mediumseagreen","mediumslateblue","mediumspringgreen","mediumturquoise","mediumvioletred","midnightblue","mintcream","mistyrose","moccasin","navajowhite","navy","navyblue","oldlace","olivedrab","orange","orchid","orengered","palegodenrod","palegreen","paleturquoise","palevioletred","papayawhip","peachpuff","peru","pink","plum","powderblue","purple","quartz","red","rosybrown","royalblue","saddlebrown","salmon","sandybrown","scarlet","seagreen","seashell","sienna","silver","skyblue","slategray","snow","springgreen","steelblue","tan","thistle","tomato","turquoise","violet","violetred","wheat","whitesmoke","yellow","yellowgreen"};
for(int i=0;i<aColors.Length;i++){
if(aColors[i].IndexOf(sInput) == 0)
sResult += aColors[i] + ",";
}
if(sResult.Length>0) //如果有匹配项
sResult = sResult.Substring(0,sResult.Length-1); //去掉最后的“,”号
Response.Write(sResult);
%>

示例二:使用jQuery 实现。
客户端:

代码如下:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>jQuery实现自动提示的文本框</title>
<style>
<!--
body{
font-family:Arial, Helvetica, sans-serif;
font-size:12px; padding:0px; margin:5px;
}
form{padding:0px; margin:0px;}
input{
/* 用户输入框的样式 */
font-family:Arial, Helvetica, sans-serif;
font-size:12px; border:1px solid #000000;
width:200px; padding:1px; margin:0px;
}
#popup{
/* 提示框div块的样式 */
position:absolute; width:202px;
color:#004a7e; font-size:12px;
font-family:Arial, Helvetica, sans-serif;
left:41px; top:25px;
}
#popup.show{
/* 显示提示框的边框 */
border:1px solid #004a7e;
}
/* 提示框的样式风格 */
ul{
list-style:none;
margin:0px; padding:0px;
color:#004a7e;
}
li.mouseOver{
background-color:#004a7e;
color:#FFFFFF;
}
-->
</style>
<script language="javascript" src="jquery.min.js"></script>
<script language="javascript">
var oInputField; //考虑到很多函数中都要使用
var oPopDiv; //因此采用全局变量的形式
var oColorsUl;
function initVars(){
//初始化变量
oInputField = $("#colors");
oPopDiv = $("#popup");
oColorsUl = $("#colors_ul");
}
function clearColors(){
//清除提示内容
oColorsUl.empty();
oPopDiv.removeClass("show");
}
function setColors(the_colors){
//显示提示框,传入的参数即为匹配出来的结果组成的数组
clearColors(); //每输入一个字母就先清除原先的提示,再继续
oPopDiv.addClass("show");
for(var i=0;i<the_colors.length;i++)
//将匹配的提示结果逐一显示给用户
oColorsUl.append($("<li>"+the_colors[i]+"</li>"));
oColorsUl.find("li").click(function(){
oInputField.val($(this).text());
clearColors();
}).hover(
function(){$(this).addClass("mouseOver");},
function(){$(this).removeClass("mouseOver");}
);
}
function findColors(){
initVars(); //初始化变量
if(oInputField.val().length > 0){
//获取异步数据
$.get("14-10.aspx",{sColor:oInputField.val()},
function(data){
var aResult = new Array();
if(data.length > 0){
aResult = data.split(",");
setColors(aResult); //显示服务器结果
}
else
clearColors();
});
}
else
clearColors(); //无输入时清除提示框(例如用户按del键)
}
</script>
</head>
<body>
<form method="post" name="myForm1">
Color: <input type="text" name="colors" id="colors" onkeyup="findColors();" />
</form>
<div id="popup">
<ul id="colors_ul"></ul>
</div>
</body>
</html>

服务器端(14-10.aspx ):


代码如下:

<%@ Page Language="C#" ContentType="text/html" ResponseEncoding="gb2312" %>
<%@ Import Namespace="System.Data" %>
<%
Response.CacheControl = "no-cache";
Response.AddHeader("Pragma","no-cache");
string sInput = Request["sColor"].Trim();
if(sInput.Length == 0)
return;
string sResult = "";
string[] aColors = new string[]{"aliceblue","antiquewith","aquamarine","azure","beige","bisque","black","blanchedalmond","blue","blueviolet","brass","bronze","brown","burlywood","cadetblue","chartreuse","chocolate","copper","coral","cornfloewrblue","cornsilk","cyan","darkblue","darkcyan","darkgoldenrod","darkgray","darkgreen","darkhaki","darkmagenta","darkolivegreen","darkorchid","darkorenge","darkred","darksalmon","darkseagreen","darkslateblue","darkslategray","darkturquoise","darkviolet","deeppink","deepskyblue","dimgray","dodgerblue","feldspar","firebrick","floralwhite","forestgreen","fuchsia","gainsboro","gold","goldenrod","golenrod","gostwhite","gray","green","greenyellow","honeydew","hotpink","indianred","inen","ivory","khaki","lavender","lavenderblush","lawngreen","lemonchiffon","lightblue","lightcoral","lightcyan","lightgodenrod","lightgodenrodyellow","lightgray","lightgreen","lightpink","lightsalmon","lightseagreen","lightskyblue","lightslateblue","lightslategray","lightsteelblue","lightyellow","lime","limegreen","magenta","magenta","maroom","maroon","mediumaquamarine","mediumblue","mediumorchid","mediumpurpul","mediumseagreen","mediumslateblue","mediumspringgreen","mediumturquoise","mediumvioletred","midnightblue","mintcream","mistyrose","moccasin","navajowhite","navy","navyblue","oldlace","olivedrab","orange","orchid","orengered","palegodenrod","palegreen","paleturquoise","palevioletred","papayawhip","peachpuff","peru","pink","plum","powderblue","purple","quartz","red","rosybrown","royalblue","saddlebrown","salmon","sandybrown","scarlet","seagreen","seashell","sienna","silver","skyblue","slategray","snow","springgreen","steelblue","tan","thistle","tomato","turquoise","violet","violetred","wheat","whitesmoke","yellow","yellowgreen"};
for(int i=0;i<aColors.Length;i++){
if(aColors[i].IndexOf(sInput) == 0)
sResult += aColors[i] + ",";
}
if(sResult.Length>0) //如果有匹配项
sResult = sResult.Substring(0,sResult.Length-1); //去掉最后的“,”号
Response.Write(sResult);
%>

(0)

相关推荐

  • JavaScript如何实现在文本框(密码框)输入提示语

    有时候我们需要在登陆表单有一些提示语言,比如"请输入用户名"和"请输入密码"等语言,至于用户名好说,但是在密码框中出现"请输入密码"这样的语言就有点麻烦了,因为在密码框输入的内容不会以明码显示.如果动态的控制type属性的话就有兼容性问题,如果input已经存在于页面中的话,在IE8和IE8以下浏览器中,type属性是只读的.所以就得想其他办法,代码如下: <!DOCTYPE html> <html> <head&g

  • javascript 输入文本框时的友好提示

    下面的代码实现当用户停留在text输入框的时候提示输入什么的提示信息,提高用户粘合度. 在输入内容前,显示如图1所示 图1 当用户名的文本框或得焦点时,效果如图2所示 图2 当密码文本框或得焦点时,效果如图3所示 图3 演示的源代码如下: tt控件演示 //tipTxt要显示的内容,apos向右移动的距离,vpos向下移动的距离 function tip(tt,tipTxt,apos,vpos){ if(apos==undefined){ var apos=0; } if(vpos==undef

  • 文本框输入时 实现自动提示(像百度、google一样)

    只要有三个文件: 一个js插件autocomplete.js和autocomplete.css两个文件,这是jquery官方网站提供的插件: 他们的下载地址:http://jqueryui.com/demos/autocomplete/ 一个是一般处理程序 : 一个是apsx页面,看下面的代码吧; 前台: 复制代码 代码如下: <script type="text/javascript"> $(document).ready(function() { ShowUserLis

  • JavaScript 文本框下拉提示(自动提示)

    文本框下拉提示效果 html{overflow:-moz-scrollbars-vertical;} body{padding:0;margin:0;font:12px/1.5 Tahoma,Helvetica,Arial,sans-serif;} body,h1,p,blockquote,dl,dt,dd,ul,ol,li,input{margin:0;padding:0;} button,input,select,textarea {font:12px/1.5 tahoma,arial,si

  • asp.net 页面版文本框智能提示JSCode (升级版)

    原本准备在上一篇中直接修改的,无奈编辑功能太差,打开一堆html代码,空格"&nbsp"都看的人眼花缭乱,只好另开一篇. 升级说明:添加了针对一个界面多个职能提示位置的设定,只需修改文本框onfocus="fnStartInterval(this,'DropDownList2')", 设置好相应的参数即可,同时修复了在IE6下div无法遮盖下拉列表的问题,(IE6下无论如何设置select的z-index或div的z-index属性均无济于事),关于这个就是

  • Flex 文本框的输入下拉提示

    复制代码 代码如下: <?xml version="1.0" encoding="utf-8"?> <mx:FormItem xmlns:mx="http://www.adobe.com/2006/mxml" label="" required="true" width="305" fontWeight="bold" height="28&

  • 页面版文本框智能提示JS代码

    于是这code便诞生了,如下: 复制代码 代码如下: <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>无标题页</title> <script type="text/javascript" language="javascript"> var currentIndex=

  • 简单JS自动提示文本框代码

    本例以颜色为例,为用户提供自动提示,展示效果和运行结果如图: 1.建立框架结构: 复制代码 代码如下: <body> <form method="post" name="myForm1"> Color: <input type="text" name="colors" id="colors" onkeyup="findColors();" /> <

  • 两种方法实现文本框输入内容提示消失

    第一种方法: 基于HTML5 input标签的新特性 - placeholder .另外,x-webkit-speech 属性可以实现语音输入功能. 复制代码 代码如下: <div><input type="email" name="email" spellcheck="false" placeholder="邮 箱" autofocus tabindex="1" x-webkit-spe

  • 基于JQuery实现鼠标点击文本框显示隐藏提示文本

    比如本人网站的搜索框: 不使用的时候: 鼠标点击后: 用JQuery实现这个效果非常简单,下面是代码: 复制代码 代码如下: $(document).ready(function () { var searchBox = $("#ctl00_txtSearch"); searchBox.focus(function () { if (searchBox.val() == this.title) { // TextBox控件ToolTip属性转换为Html为title属性 searchB

随机推荐