需求:前面写了一个简单的表单检验,需要用户提交信息后才会对表单信息进行检验,下面我们增加对用户的提供友好提示,即输入时就为表单信息进行检验,并提供提示信息。
步骤分析:1. 导入JQ的文件
2. 文档加载事件: 在必填项后天加一个小红点
3. 表单校验确定事件: blur focus keyup
4. 提交表单 submit
源码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="../css/style.css" />
<title></title>
<script type="text/javascript" src="../js/jquery-1.11.0.js" ></script>
<script>
$(function(){ //默认做一些页面初始化
//动态在必填项后面添加小红点
$(".bitian").after("<font class='high'>*</font>");
//给必填项绑定事件
$(".bitian").blur(function(){
//首先获取用户当前输入的值
var value = this.value; //123
//清空上一次提示的信息
$(this).parent().find(".formtips").remove();
//判断当前的值是哪一项输入的值
if($(this).is("#username")){ //判断是否是用户名输入项
if(value.length < 6){
$(this).parent().append("<span class='formtips onError'>用户名太短了</span>");
}else{
$(this).parent().append("<span class='formtips onSuccess'>用户名够用</span>");
}
}
if($(this).is("#password")){ //判断是否是密码输入项
if(value.length < 6){
$(this).parent().append("<span class='formtips onError'>,密码太短了</span>");
}else{
$(this).parent().append("<span class='formtips onSuccess'>密码够用</span>");
}
}
}).focus(function(){
$(this).triggerHandler("blur");
}).keyup(function(){
$(this).triggerHandler("blur");
})
//给表单提交绑定事件
$("form").submit(function(){
//触发所有必填项的校验
$(".bitian").trigger("focus");
//找到错误信息的个数
if($(".onError").length > 0){
return false;
}
return true;
});
});
/*
$(function(){
// 在所有必填项后天加一个小红点 *
$(".bitian").after("<font class='high'>*</font>");
//事件绑定
$(".bitian").blur(function(){
// var value = this.value;
var value = $(this).val();
//清空当前必填项后面的span
// $(".formtips").remove();
$(this).parent().find(".formtips").remove();
//获得当前事件是谁的
if($(this).is("#username")){
//校验用户名
if(value.length < 6){
$(this).parent().append("<span class='formtips onError'>用户名太短了</span>");
}else{
$(this).parent().append("<span class='formtips onSuccess'>用户名够用</span>");
}
}
if($(this).is("#password")){
//校验密码
if(value.length < 3){
$(this).parent().append("<span class='formtips onError'>密码太短了</span>");
}else{
$(this).parent().append("<span class='formtips onSuccess'>密码够用</span>");
}
}
}).focus(function(){
$(this).triggerHandler("blur");
}).keyup(function(){
$(this).triggerHandler("blur");
});
// $(".bitian").blur(function(){}).focus(function(){}).keyup(function(){})
//给表单绑定提交事件
$("form").submit(function(){
//触发必填项的校验逻辑
$(".bitian").trigger("focus");
var length = $(".onError").length
if(length > 0){
return false;
}
return true;
});
});*/
</script>
</head>
<body>
<form action="../index.html">
<div>
用户名:<input type="text" class="bitian" id="username" />
</div>
<div>
密码:<input type="password" class="bitian" id="password" />
</div>
<div>
手机号:<input type="tel" />
</div>
<div>
<input type="submit" />
</div>
</form>
</body>
</html>
示例: