延迟Parsley.js表单提交



我需要能够在提交时验证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方法可以提交表单而无需重新验证?

根据这个问题,一旦一个动作被取消(使用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>

我正在积极地进行更新,将处理承诺,所以你想要实现的将是非常容易做到的。

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

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

最新更新