本人也是JQuery初学者,写了个用户名无刷新验证的简单例子,拿来分享,共同学习一下吧。
1.在静态页面里添加文本框及样式和js脚本的引用:
代码
< html xmlns ="http://www.w3.org/1999/xhtml" >
< head id ="Head1" runat ="server" >
< title > 无标题页 </ title >
< script language ="javascript" src ="../jquery-1.3.2.min.js" type ="text/javascript" ></ script >
< script language ="javascript" src ="validator.js" type ="text/javascript" ></ script >
< link type ="text/css" rel ="stylesheet" href ="validator.css" />
</ head >
< body >
< form id ="form1" runat ="server" >
< div >
用户名: < input id ="txtName" type ="text" class ="txtName" />
< div id ="result" ></ div >
</ div >
</ form >
</ body >
</ html >
< html xmlns ="http://www.w3.org/1999/xhtml" >
< head id ="Head1" runat ="server" >
< title > 无标题页 </ title >
< script language ="javascript" src ="../jquery-1.3.2.min.js" type ="text/javascript" ></ script >
< script language ="javascript" src ="validator.js" type ="text/javascript" ></ script >
< link type ="text/css" rel ="stylesheet" href ="validator.css" />
</ head >
< body >
< form id ="form1" runat ="server" >
< div >
用户名: < input id ="txtName" type ="text" class ="txtName" />
< div id ="result" ></ div >
</ div >
</ form >
</ body >
</ html >
2.css样式表,当文本框文字为空时边框红色:
.txtName
{
border : 1px red solid ;
}
{
border : 1px red solid ;
}
3.js脚本:当文本框文字为空时边框红色;如果用户名为janes,则提示“用户名已经存在”,否则提示“用户名可以使用”。
代码
$(
function
(){
var txtname = $( " #txtName " );
// 输入文字时文本框样式
txtname.keyup( function (){
var name = $( this ).val();
if (name == "" )
$( this ).addClass( " txtName " );
else $( this ).removeClass( " txtName " );
})
// 失去焦点时验证用户名是否可用
$( " #txtName " ).blur( function ()
{
var name = $( this ).val();
$.get( " validator1.aspx?name= " + name, null , function (response){
$( " #result " ).html(response);
})
})
})
var txtname = $( " #txtName " );
// 输入文字时文本框样式
txtname.keyup( function (){
var name = $( this ).val();
if (name == "" )
$( this ).addClass( " txtName " );
else $( this ).removeClass( " txtName " );
})
// 失去焦点时验证用户名是否可用
$( " #txtName " ).blur( function ()
{
var name = $( this ).val();
$.get( " validator1.aspx?name= " + name, null , function (response){
$( " #result " ).html(response);
})
})
})
4..aspx及.cs页面代码,用来验证用户名是否可用,以返回结果。
.cs代码
public
partial
class
Validator_validator1 : System.Web.UI.Page
{
protected void Page_Load( object sender, EventArgs e)
{
string name = Request.QueryString[ " name " ].ToString();
if (name == " janes " )
Response.Write( " 该用户名已经存在! " );
else
Response.Write( " 该用户名可以使用! " );
}
}
{
protected void Page_Load( object sender, EventArgs e)
{
string name = Request.QueryString[ " name " ].ToString();
if (name == " janes " )
Response.Write( " 该用户名已经存在! " );
else
Response.Write( " 该用户名可以使用! " );
}
}