方法1:<form onsubmit="javascript:confirm()"> 方法內返回false阻止表單提交
示例:代碼檢測textarea內填寫的長度,未填寫時提示需要重新填寫,少於15字符時提示需要長於15字符,成功時顯示所填寫建議。
1 <script type="text/javascript"> 2 //jQuery代碼 3 function confirm() 4 { 5 if($("#advice").val().length == 0) 6 { 7 alert("We can't see your advice. Maybe you should fill the form first."); 8 $("#advice").focus(); 9 return false; 10 } 11 else if($("#advice").val().length <= 15) 12 { 13 alert("Your advice should longer than 15 letters."); 14 $("#advice").focus(); 15 return false; 16 } 17 else 18 { 19 alert("Thank you for your advice! You will get out reply in 24 hours for advice:\n"+$("#advice").val()); 20 return true; 21 } 22 23 } 24 </script> 25 26 <form action="" method="post" onSubmit="return confirm();" > 27 <textarea id="advice" rows="20" cols="50"placeholder="Give us some advice?"></textarea> 28 <input type="submit"value="Thank you"/> 29 </form>
>關鍵點
1.必須要有onSubmit="return confirm();" return 這個詞,不可缺少。
2.自行完整的網頁結構。
方法二:<form onsubmit="javascript:checkContent(this, event)"> 方法內返回false阻止表單提交
evt.preventDefault(); 使用JQuery event對象的方法preventDefault()阻止默認行為
參考W3School教程
示例:
<script type="text/javascript"> //jQuery代碼 function checkContent(form, evt) { if($("#advice").val().length == 0) { alert("We can't see your advice. Maybe you should fill the form first."); $("#advice").focus(); evt.preventDefault(); }else if($("#advice").val().length <= 15) { alert("Your advice should longer than 15 letters."); $("#advice").focus(); evt.preventDefault();
} else {
alert("Thank you for your advice! You will get out reply in 24 hours for advice:\n"+$("#advice").val());
}
}
</script>
<form action="" method="post" onSubmit="javascript:checkContent(this, event)" >
<textarea id="advice" rows="20" cols="50" placeholder="Give us some advice?"></textarea>
<input type="submit" value="Thank you"/>
</form>
