JQuery阻止表单提交的方法总结 - 使用onsubmit()验证表单并阻止非法提交

时间:2022-12-02 18:55:35

方法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()阻止默认行为

JQuery阻止表单提交的方法总结 - 使用onsubmit()验证表单并阻止非法提交

参考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>