【问题标题】:jQuery submit form and then disable all 'input[type="submit"]' to prevent duplicate submissionsjQuery 提交表单,然后禁用所有 'input[type="submit"]' 以防止重复提交
【发布时间】:2015-01-09 00:03:41
【问题描述】:

我有一个奇怪的问题,常见的解决方案似乎无法解决。当用户单击基于 html 的表单时,我会遇到一些奇怪的行为,如果他们单击“保存”、“上一个”或“下一个”,则会提交该表单。

<div class="form-tab-nav form-tab-nav-bottom">
  <input id="tab" name="tab" tabindex="25" type="hidden" value="3">
  <input name="commit" tabindex="26" type="submit" value="Save">
    <input id="prev_commit_bottom" name="prev_commit[bottom]" tabindex="27" type="submit" value="<< Prev">
  <input class="orange" id="next_commit_bottom" name="next_commit[bottom]" tabindex="28" type="submit" value="Next >>">
</div>

使用 jQuery 1.6.1:

$('form').submit(function() {
  $(this).find("input[type='submit']").prop('disabled',true);
});

这将禁用该按钮,从而不允许第二个发布请求,但它会禁用重定向。也就是说,点击“上一个”或“下一个”的行为与点击“保存”的行为相同。

【问题讨论】:

  • 因为您在提交之前禁用了表单,所以什么都不会发生。
  • 我无法重现该问题:jsfiddle.net/jxv7un8c/5

标签: javascript jquery html forms


【解决方案1】:

因为您在提交之前禁用了表单,所以什么都不会发生。您必须设置超时以允许提交发生。

$('form').submit(function() {
    var after = $.proxy(function () {
        $(this).find("input[type='submit']").prop('disabled',true);
    },this);
    window.setTimeout(after,50);
});

$('form').submit(function() {
    var elems = $(this).find("input[type='submit']");
    var after = function () {
        elems.prop('disabled',true);
    };
    window.setTimeout(after,50);
});

【讨论】:

  • 我有一个页面使用纯 Javascript 而不是 jQuery 禁用提交按钮,它工作得很好。使用 jQuery 有什么不同吗?
  • jQuery 是 JavaScript...所以它可能在幕后做同样的事情。
  • 这就是我的观点。当我这样做时,它不会阻止表单提交。为什么 jQuery 需要计时器?
  • 我有点认为这是问题所在,但我觉得必须有比使用 setTimeout 更好的解决方案?
【解决方案2】:

感谢大家的帮助,但这是解决我们重复提交问题的解决方案:

  $('form').submit(function(e) {
    var $form = $(this);
    if ($form.data('submitted') === true) {
      e.preventDefault();
    } else {
      $form.data('submitted', true);
    }
  });

【讨论】:

    【解决方案3】:

    代替这一行

    <input id="prev_commit_bottom" name="prev_commit[bottom]" tabindex="27" type="submit" value="<< Prev">
    

    试试这个

    <input id="prev_commit_bottom" name="prev_commit[bottom]" tabindex="27" type="submit" value="&lt;&lt; Prev">
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-12
      • 1970-01-01
      • 2011-02-19
      • 2011-06-04
      相关资源
      最近更新 更多