【问题标题】:Form: disabling submit button upon click, form is not submitted表单:单击时禁用提交按钮,表单未提交
【发布时间】:2015-01-07 18:52:46
【问题描述】:

我想禁用提交按钮以防止重复提交。

为此,我使用 jQuery:

jQuery('#subnewtopicform').on('submit', function () {
    jQuery('#subnewtopic').prop('disabled', true);
});

并剥离 HTML:

    <form action="" method="post" id="subnewtopicform">
        <input type="text" name="title" />
        <input type="submit" value="Submit" name="subnewtopic" id="subnewtopic" /> 
    </form>

当点击提交按钮时,它被禁用并且页面重新加载但表单没有提交,为什么?!这对我来说是一个很大的谜。

【问题讨论】:

  • 表单提交是导致页面重新加载的原因......那你为什么说它没有提交?需要提供有关预期内容的更多信息
  • @charlietfl 这就是为什么这是一个谜。好像提交按钮会在提交表单或类似的东西时剥离所有传输的数据......?
  • 不,您的问题出在其他地方。活动页面是否应该是表单的action url?
  • @charlietfl 是的。我应该注意,当我删除这个非常 jQuery 代码时,一切正常。
  • 更改帖子以获取并点击提交,然后您会在 url 中看到表单是否正在提交数据

标签: jquery html forms


【解决方案1】:

我们在双击表单时遇到了很多问题,所以我使用了一个带有计时器的 HTML5 数据变量,它基本上会在 N 次内禁用按钮。如果您将此时间设置得非常高,它将有效地禁用按钮再次执行任何操作,而不会实际禁用提交按钮本身。

然后您可以使用 JS 函数本身提交表单。

    jQuery('#subnewtopicform').on('submit', function (e) {
        e.preventDefault(); 
        //prevent double clicking 
        if (!$(this).data('isClicked')) {
            //store it for later in case of async
            var link = $(this);             

            // Set the isClicked value and set a timer to reset and be re-clickable in 3seconds
            link.data('isClicked', true);
            setTimeout(function() {
                link.removeData('isClicked')
            }, 3000);

           //submit the form with JS
           //your form tag should have action and method on the html for this to go anywhere
           $(this).submit();
        }
        else {
            return false;
        }
    });

【讨论】:

  • 这使得提交按钮不起作用...?=
  • 对,如前所述,这是为使用javascript提交表单而设计的。我会更新答案以更清楚。
【解决方案2】:

我使用输入的 'onclick' 属性,因为我不能使用 jQuery。 onclick 也常用于表单提交前验证数据

<input type="submit" value="Submit" name="subnewtopic" id="subnewtopic" onclick=" return disableButton();" /> 

对于您的 JavaScript:

<script>
function disableButton() {
var button = document.getElementById('subnewtopic');
button.disabled = true; 
return true;
}
</script>

return true 告诉表单在函数完成后提交。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-03
    • 1970-01-01
    • 2023-03-21
    • 2016-04-03
    • 2018-06-30
    • 1970-01-01
    • 2010-09-11
    相关资源
    最近更新 更多