表单提交前,肯定要进行判断;如果检测失败,将阻止表单的默认提交!
有两种方法:
【1】使用 onsubmit
- form 表单如下:
<form action="postServlet5" method="post" onsubmit="return check()">
<input type="text" name="username" id="username"/>
<input type="submit" value="submit"/>
</form>
-
JS 如下:
如果不返回return,将不会阻止表单的默认提交动作!
var check = function(){
//typeof "" ==string typeof null == object
if(($("#username").val() != "" )&&($("#username").val()!= null)){
alert("it's not null");
return true;
}else if(($("#username").val() == "" )||($("#username").val()== null)){
alert("it's null");
return false;
}
}
【2】不使用 onsubmit
- 监控按钮点击事件;
<form action="postServlet5" method="post" >
<input type="text" name="username" id="username"/>
<input type="submit" value="submit"/>
</form>
- JS 第一种:
window.onload = function(){
$("input[type='submit']").click(function(){
if($("input[type='username']").val() != "" && $("input[type='username']").valu != null){
alert("验证通过");
return true;
//返回true提交表单
}else{
alert("验证不通过");
return false;
//返回false不提交,不返还false是不会阻止表单的默认提交动作
}
});
}
- JS 第二种:
window.onload = function(){
$("input[type='submit']").click(function(){
if(check()){
alert("验证通过!")
return true;
}else{
alert("验证不通过!")
return false;
//如果不返回return是不会阻止submit的默认动作的!
}
});
}
//单独写一个函数判断--推荐!
var check = function(){
//typeof "" ==string typeof null == object
if(($("#username").val() != "" )&&($("#username").val()!= null)){
alert("it's not null");
return true;
}else if(($("#username").val() == "" )||($("#username").val()== null)){
alert("it's null");
return false;
}
}