表单:单击时禁用提交按钮,表单未提交

时间:2015-01-07 18:52:47

标签: jquery html forms

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

为此,我使用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>

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

2 个答案:

答案 0 :(得分:0)

双击表单存在大量问题,因此我使用带有计时器的HTML5数据var,这基本上会禁用 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;
        }
    });

答案 1 :(得分:0)

我使用输入&#39; onclick&#39;属性,因为我不能使用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告诉表单在函数完成后提交。