天天看点

阻止自动表单提交

html:

<!doctype html>
<html>
 <head>
	<meta charset="UTF-8">
	<title>阻止自动表单提交</title>
	<link rel="Stylesheet" href="css/5.css" target="_blank" rel="external nofollow"  />
	<script src="js/5.js"></script>
 </head>
 <body>
	<!--1. 使用HTML绑定事件处理函数时-->
	<form id="form1">
		<h2>增加管理员</h2>
		<table>
			<tr>
				<td>姓名:</td><td>
<input name="username" οnfοcus="getFocus(this)"
οnblur="valiName(this)"/>
					<span>*</span>
				</td>
				<td>
					<div class="vali_Info">
						10个字符以内的字母、数字和下划线的组合
					</div>
				</td>
			</tr>
			<tr>
				<td>密码:</td>
				<td>
<input type="password" name="pwd"  οnfοcus="getFocus(this)" οnblur="valiPwd(this)"/>
					<span>*</span>
				</td>
				<td>
					<div class="vali_Info">6位数字</div>
				</td>
			</tr>
			<tr>
				<td></td>
				<td colspan="2">
<!--取消事件,2个return-->
<input type="submit" value="保存"/>
<input type="reset" value="重填"/>
				</td>
			</tr>				
	    </table>
	</form>
 </body>
</html>
           

js:

function getFocus(txt){
	txt.className="txt_focus";
	txt.parentNode //td
		.parentNode //tr
		.querySelector("div")
			.className="";
}
function valiName(txt){
	txt.className="";
	var div=txt.parentNode //td
				.parentNode //tr
				.querySelector("div");
	if(/^\w{1,10}$/.test(txt.value)){
		div.className="vali_success";
		return true;
	}else{//否则
		div.className="vali_fail";
		return false;
	}
}
function valiPwd(txt){
	txt.className="";
	var div=txt.parentNode //td
				.parentNode //tr
				.querySelector("div");
	if(/^\d{6}$/.test(txt.value)){
		div.className="vali_success";
		return true;
	}else{//否则
		div.className="vali_fail";
		return false;
	}
}
function valiAll(e){//验证所有
  //this->form1
  var rName=valiName(this.username);
  var rPwd=valiPwd(this.pwd);
  if(!(rName&&rPwd)){//如果验证结果不全为true
    e.preventDefault();//就取消事件
  }
}
window.οnlοad=function(){
  form1.addEventListener("submit",valiAll);
}
           

css:

table{width:700px}
/*父元素下的第1个,第n个,最后一个td子元素*/
td:first-child{width:60px}
/*IE不支持nth-child*/
td:nth-child(2){width:200px}
/*IE*/
td:first-child+td{width:200px}
/*IE不支持--可以靠总宽度来调节
td:last-child{width:340px}*/
td span{color:red}

.vali_Info{/* 页面初始,验证消息不显示 */
	display:none;
}
.txt_focus{
	border-top:2px solid black;
	border-left:2px solid black;
}

.vali_success,.vali_fail{
	background-repeat:no-repeat;
    background-position:left center;
	display:block;
}
/* 验证消息:验证通过时的样式 */
.vali_success{
    background-image:url("../images/ok.png");
	padding-left:20px;
	width:0px;height:20px;
	overflow:hidden;
}
/* 验证消息:验证失败时的样式 */
.vali_fail{
    background-image:url("../images/warning.png");
    border:1px solid red;
    background-color:#ddd;
    color:Red;
    padding-left:30px;
}
           

效果:

没有填写内容不能提交