有错误信息的时候提交焦点会返回错误处,点击重置表单和提示信息都重置
代码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="../jquery-1.8.3.min.js"></script>
<title></title>
<style>
form>p{
font: 14px;
color: #333;
line-height: 30px;
}
span.default{
color: #f00;
}
span.w{
color: #f00;
background: url(../img/reg3.gif) no-repeat left center;
padding-left: 25px;
}
span.r{
color: #0f0;
background: url(../img/reg4.gif) no-repeat left center;
padding-left: 25px;
}
</style>
</head>
<body>
<form name="form1">
<p>用户名:<input type="text" name="username" /><span id="namemsg" class="default">*</span><br></p>
<p>手机号:<input type="text" name="tel" /><span id="telmsg" class="default">*</span><br></p>
<p>邮箱:<input type="text" name="email" /><span class="default">*</span></p>
<p><input type="submit" value="提交" name="sub" />
<input type="reset" value="重置" name="rest"/></p>
</form>
</body>
<script>
$(function(){
var rmsg="输入正确";
$("input[name=username]").keyup(function(){
var reg_name=/^\w{3,30}$/;
if(reg_name.test($(this).val())){
$(this).next("span").html(rmsg).attr("class","r");
}else{
$(this).next("span").html("请输入3-30位的字母数字名称").attr("class","w");
}
})
$("input[name=tel]").keyup(function(){
var reg_tel=/^(13|15|17|18|19)\d{9}$/;
if(reg_tel.test($(this).val())){
$(this).next("span").html(rmsg).attr("class","r");
}else{
$(this).next("span").html("请输入正确的手机号").attr("class","w");
}
})
$("input[name=email]").keyup(function(){
var reg_email=/^\w+@\w+(\.com|\.cn)$/;
if(reg_email.test($(this).val())){
$(this).next("span").html(rmsg).attr("class","r");
}else{
$(this).next("span").html("请输入正确的邮箱").attr("class","w");
}
})
//提交验证
$("form[name=form1]").submit(function(event){//js兼容性写法:e=e||window.event
if(!($("input[name=username]").next("span").hasClass("r"))){
$("input[name=username]").triggerHandler("keyup");
event.preventDefault();//同return false;
}
if(!($("input[name=tel]").next("span").hasClass("r"))){
$("input[name=tel]").triggerHandler("keyup");
return false;
}
if(!($("input[name=email]").next("span").hasClass("r"))){
$("input[name=email]").triggerHandler("keyup");
return false;
}
})
//重置
$("input[name=rest]").click(function(){
$("input[name=username]").next("span").html("*").attr("class","default");
$("input[name=tel]").next("span").html("*").attr("class","default");
$("input[name=email]").next("span").html("*").attr("class","default");
})
})
</script>
</html>
网友评论