【问题标题】:How to reset validation after the form is submitted with AJAX? [duplicate]使用 AJAX 提交表单后如何重置验证? [复制]
【发布时间】:2013-09-12 16:43:51
【问题描述】:

我有一个用 html5 验证验证的表单,然后用 AJAX 提交,然后输入字段被重置,它正在工作。

我的问题是,在有效提交后,发送了消息,清除了输入,但 html5 验证仍然将我的空字段概述为不正确的字段。

HTML:

 <form method="post" action="mailer.php" class="contact-form" id="cform">
     <input type="text" name="name" placeholder="Name" required />
     <input type="text" name="phone"  placeholder="Phone" required />                       
     <input type="email" name="email" placeholder="Email" required />                       
     <textarea name="message" placeholder="Message" required></textarea>
     <input type="submit" class="submit-btn" id="submit-btn" value="Send your message" />
     <div id="success"></div>
 </form>

查询:

 $('#submit-btn').click(function(){
     if($("#cform")[0].checkValidity()) {

         $.post("mailer.php", $("#cform").serialize(),  function(response) {
             $('#success').html(response);
             $("#cform")[0].reset();
         });
         return false;

     } else console.log("invalid form");
 });

【问题讨论】:

标签: jquery ajax html forms


【解决方案1】:

您需要停止默认的提交行为。

 $('#submit-btn').click(function(e){
     e.preventDefault();
     // ...
 }

或者您可以只使用type="button" 而不是type="submit"

【讨论】:

  • 这就是 return false 所做的
  • 这完全禁用了 html5 验证。
【解决方案2】:

我强烈建议你使用提交事件

如果您使用新的 HTML5 验证(例如需要),您的 .reset() 应该可以工作。

它适用于我Live Demo

$(function() {
  $('#cform').on("submit",function(e){
    e.preventDefault();  
    if($("#cform")[0].checkValidity()) {
      $.post("/echo/json/", $("#cform").serialize(),function(response) {
        $('#success').html(response);
        $("#cform")[0].reset();
      });
     }
     else window.console &&  console.log("invalid form");
   });
 });    

如果没有,请尝试聚焦并模糊每个字段,以告诉验证器字段正常,

How to clear, remove, or reset HTML5 form validation state after "setCustomValidity("...");"?

如果你使用jQUery validation plugin,你需要做一个resetForm()

【讨论】:

  • 试过这个,但不幸的是没有奏效。表单提交成功并清除字段后,表单字段仍以红色勾勒。
  • 感谢您的好意和重建我的问题。我的网站与您的演示 jsfiddle 完全一样,在提交消息后,字段显示为错误字段。顺便说一句,如果这太复杂了,我可以考虑使用验证插件 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-04-10
  • 2016-01-03
  • 2014-06-11
  • 1970-01-01
  • 1970-01-01
  • 2019-06-18
  • 1970-01-01
相关资源
最近更新 更多