【问题标题】:How to keep submit buttons disabled on remote forms until the next page has loaded如何在加载下一页之前保持禁用远程表单上的提交按钮
【发布时间】:2018-03-31 14:06:25
【问题描述】:

在我使用 Turbolinks 的 Rails 5.1 应用程序中,我为我的提交按钮添加了一个 data-disable-with 属性,以便在单击时按钮将被禁用,以防止意外多次提交数据。这在很多情况下都很有效。

问题在于,在使用内置 UJS 帮助程序 (data-remote=true) 通过 AJAX 提交的表单上,当单击提交按钮时,它不会保持禁用状态。它最初被禁用,但在加载下一页之前很快重新启用。这违背了data-disable-with 行为的意义,因为它会导致意外的表单重新提交。

有没有办法在新页面加载之前保持表单按钮处于禁用状态?

这是表格:

<%= simple_form_for(
  resource,
  as: resource_name,
  url: session_path(resource_name),
  html: { class: "large", autocomplete: "on" },
  remote: true
) do |f| %>
  <%= f.input(
    :email,
    placeholder: "Email address",
    label: false,
    autofocus: true
  ) %>
  <%= f.input(:password, placeholder: "Password", label: false) %>
  <%= f.button(
    :submit,
    "Sign in",
    class: "ui fluid large teal submit button",
    "data-disable-with": "Signing in..."
  ) %>
<% end %>

这就是发生的事情。

【问题讨论】:

  • 我们要从那个动画中直觉你的代码吗?
  • @jvillian @patrick-ogrady 在描述中已经注意到他在表单上使用了data-remote=true 属性,以及按钮上的data-disable-with 属性,我觉得从代码视角。它缺少一个明确的问题,我希望我能帮助澄清。
  • 感谢@DomChristie,我还添加了表单的代​​码。

标签: javascript ruby-on-rails turbolinks ujs


【解决方案1】:

发生了什么?

  1. 表单已提交
  2. rails-ujs 禁用按钮(data-disable-with 行为)
  3. 表单请求成功
  4. rails-ujs 重新启用按钮
  5. turbolinks-rails 向重定向位置发出请求(这可能是一个缓慢的请求,使按钮处于启用状态)

解决方案

我们需要在第 4 步之后重新禁用该按钮。为此,我们将监听ajax:success 事件,并使用setTimeout 禁用它。这确保了它会在 Rails 完成它的操作之后被禁用。 (您可以使用requestAnimationFrame 代替setTimeout,但它没有得到广泛支持。)

为防止按钮在禁用状态下被缓存,我们将在它被缓存之前重新启用它。 (注意使用one 而不是on 以防止缓存前处理程序执行多次。)

我注意到您使用的是 jQuery 和 jquery-ujs,因此我将在下面的代码中使用这些库中的函数。在你的主 JavaScript 文件中包含这个。

jquery-ujs

;(function () {
  var $doc = $(document)

  $doc.on('submit', 'form[data-remote=true]', function () {
    var $form = $(this)
    var $button = $form.find('[data-disable-with]')
    if (!$button.length) return

    $form.on('ajax:complete', function () {
      // Use setTimeout to prevent race-condition when Rails re-enables the button
      setTimeout(function () {
        $.rails.disableFormElement($button)
      }, 0)
    })

    // Prevent button from being cached in disabled state
    $doc.one('turbolinks:before-cache', function () {
      $.rails.enableFormElement($button)
    })
  })
})()

rails-ujs / jQuery

;(function () {
  var $doc = $(document)

  $doc.on('ajax:send', 'form[data-remote=true]', function () {
    var $form = $(this)
    var $button = $form.find('[data-disable-with]')
    if (!$button.length) return

    $form.on('ajax:complete', function () {
      // Use setTimeout to prevent race-condition when Rails re-enables the button
      setTimeout(function () {
        $button.each(function () { Rails.disableElement(this) })
      }, 0)
    })

    // Prevent button from being cached in disabled state
    $doc.one('turbolinks:before-cache', function () {
      $button.each(function () { Rails.enableElement(this) })
    })
  })
})()

rails-ujs / vanilla JS

Rails.delegate(document, 'form[data-remote=true]', 'ajax:send', function (event) {
  var form = event.target
  var buttons = form.querySelectorAll('[data-disable-with]')
  if (!buttons.length) return

  function disableButtons () {
    buttons.forEach(function (button) { Rails.disableElement(button) })
  }

  function enableButtons () {
    buttons.forEach(function (button) { Rails.enableElement(button) })
  }

  function beforeCache () {
    enableButtons()
    document.removeEventListener('turbolinks:before-cache', beforeCache)
  }

  form.addEventListener('ajax:complete', function () {
    // Use setTimeout to prevent race-condition when Rails re-enables the button
    setTimeout(disableButtons, 0)
  })

  // Prevent button from being cached in disabled state
  document.addEventListener('turbolinks:before-cache', beforeCache)
})

请注意,这将禁用按钮,直到下一页加载到所有带有 data-disable-with 按钮的 data-remote 表单上。您可能希望更改 jQuery 选择器以仅将此行为添加到选定的表单。

希望有帮助!

【讨论】:

  • 谢谢@dom-christie!!!快速提问:如果我们不使用 jquery-ujs,而是使用 Rails 5.1 中使用 vanilla javascript 的新 UJS,解决方案会改变吗? (我们一般还是用jQuery,只是不用jquery-ujs)
  • @PatrickO'Grady 基本上是一样的。使用ajax:send而不是submit(这可能也适用于jquery-ujs,但我没有测试过),并且禁用/启用方法已更改为Rails.disableElement/Rails.enableElement。我在上面添加了一个 rails-ujs 版本。
  • @DomChristie 现在这个 PR 已经修复,还需要这个变通方法吗? github.com/rails/rails/pull/31441
【解决方案2】:

仅供参考:这是 Rails "rails-ujs prematurely enables disabled elements for XHR requests with redirects" 的一个已知问题。

还有两个 PR 可以修复它:#1#2

希望在不久的将来您不需要任何解决方法。

【讨论】:

  • 虽然此链接可能会回答问题,但最好在此处包含答案的基本部分并提供链接以供参考。如果链接页面发生更改,仅链接答案可能会失效。 - From Review
  • 我理解并理解您的观点。但是这些链接仅包含 Turbolinks 库上的代码更改,库的用户对它们无能为力。也许这个答案可能只是对第一个答案的评论,但不幸的是,我还不能评论 Stack Overflow。
  • 这刚刚在 Rails 中修复:github.com/rails/rails/pull/31441 和 turbolinks-rails:github.com/turbolinks/turbolinks-rails/pull/28。现在我们必须等待 Rails 6 和新版本的 turbolinks-rails :)。
【解决方案3】:

如何提交表单数据和禁用按钮。

<form method="post" enctype="multipart/form-data" action="action.php">
    <div class="panel panel-primary">
        <div class="panel-heading">
            <h3 class="panel-title"> submit and disabled button </h3>
        </div>
        <div class="panel-body">
            {% csrf_token %}
            <div class="form-group">
                <label>Montant</label>
                <input type="number" name="montant" id="montant" required/>
            </div>
            <div class="form-group">
                <center><span id="msgError"></span></center>
            </div>
        </div>
    </div>
<div class="form-group">
    <button type="submit" name="save" id="save">Enregistrer</button>
</div>

</form>`

<script>

    $(document).ready(function(){
        var count = 0;
        $('#save').click(function(){
           var montant = $('#montant').val();
           if (montant!=''){
               count++;
               var montant = $('#montant').val();
               // first click data are sending
               if (count == 1){
                  return true;
               }else{
               // disable button 
                  $('#msgError').text('Merci de patienter...');
                  $('#msgError').css('color', 'blue');
                  $('#save').attr('disabled', 'disabled');
               }
           }
        });
   });
</script>

【讨论】:

    猜你喜欢
    • 2017-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-21
    • 2023-03-21
    • 2013-10-14
    相关资源
    最近更新 更多