表單送出前,肯定要進行判斷;如果檢測失敗,将阻止表單的預設送出!
有兩種方法:
【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;
}
}