zoukankan      html  css  js  c++  java
  • JQuery阻止表单提交的方法总结

    方法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: "+$("#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: "+$("#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>
  • 相关阅读:
    1022. D进制的A+B (20)
    1032. 挖掘机技术哪家强(20)
    1001. 害死人不偿命的(3n+1)猜想 (15)
    结构-06. 复数四则运算(15)
    结构-05. 有理数均值(20)
    结构-04. 通讯录的录入与显示(10)
    结构-03. 平面向量加法(10)
    软考错题合集之13-05-AM
    软考笔记第八天之法律发规与标准化知识
    软考笔记第七天之程序设计语言与语言处理程序基础
  • 原文地址:https://www.cnblogs.com/AndrewXu/p/4631521.html
Copyright © 2011-2022 走看看