【问题标题】:Delay Parsley.js form submission延迟 Parsley.js 表单提交
【发布时间】:2015-08-16 06:13:34
【问题描述】:

我需要能够在提交时验证 Parsley 中的表单,但要延迟实际提交本身,直到完成其他一些(定时)操作。

我试过这个:

$("#myform").on('submit', function(e){
    e.preventDefault();
    var form = $(this);

    form.parsley().validate();

    if (form.parsley().isValid()){

        // do something here...

        setTimeout(function() {
            form.submit();
        }, 3000);

    }
});

您可能已经猜到了,form.submit() 只是让我进入了一个无限循环。如果不召回验证,我无法确定如何在延迟后触发提交。为了清楚起见,我需要:

  1. 检查表单是否有效
  2. 做一些无关的事情
  3. 等待 X 秒
  4. 提交表单

有什么想法吗?是否有 Parsley 特定的方法可以在不重新验证的情况下提交表单?

【问题讨论】:

    标签: jquery parsley.js


    【解决方案1】:

    根据this question,一旦取消操作(使用preventDefault()),唯一的选择就是再次触发它。

    你已经在这样做了。您需要添加到逻辑中的是事件是否应该停止的条件。你可以使用这样的东西:

    $(document).ready(function() {
      $("form").parsley();
    
      // By default, we won't submit the form.
      var submitForm = false;
    
      $("#myform").on('submit', function(e) {
        // If our variable is false, stop the default action. 
        // The first time 'submit' is triggered, we should prevent the default action
        if (!submitForm) {
          e.preventDefault();
        }
        var form = $(this);
    
        form.parsley().validate();
    
        // If the form is valid
        if (form.parsley().isValid()) {
          // Set the variable to true, so that when the 'submit' is triggered again, it doesn't
          // prevent the default action
          submitForm = true;
          // do something here...
    
          setTimeout(function() {
            // Trigger form submit
            form.submit();
          }, 3000);
    
        } else {
          // There could be times when the form is valid and then becames invalid. In these cases,
          // set the variable to false again.
          submitForm = false;
        }
      });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/parsley.js/2.0.7/parsley.min.js"></script>
    <form id="myform">
      <input type="text" name="field" required />
      <input type="submit" />
    </form>

    【讨论】:

    • 感谢 Milz,这实际上就是我所做的。我不确定是否有通过提交事件的内部方法,但似乎没有,所以我将其标记为已接受,因为它解决了问题。
    【解决方案2】:

    我正在积极开发一个可以处理 Promise 的更新,所以你想要实现的目标很容易实现。

    与此同时,这更难做到。我认为使用remote 版本,您可以发送提交事件,如下所示:

    $('.your-form').trigger($.extend($.Event('submit'), { parsley: true }))
    

    【讨论】:

    • 感谢 Marc 的更新,我一定会继续关注的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-04
    • 1970-01-01
    • 1970-01-01
    • 2013-03-22
    • 1970-01-01
    • 2012-05-11
    相关资源
    最近更新 更多