点击后停止提交按钮表格正确提交

时间:2015-01-07 20:25:40

标签: jquery html forms

拼图解决方案之一。

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

为此,我使用jQuery:

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

并删除了HTML:

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

单击“提交”按钮时,它会被禁用,页面会重新加载,但表单未正确提交,为什么?!删除jQuery代码将使其正确提交。

在我10年的编码中,我还没有遇到过这么奇怪的事情。

2 个答案:

答案 0 :(得分:3)

尝试使用此代码。我没有收到错误。

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

<script src="assets/js/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
    $('#subnewtopicform').on('submit', function(e) {
        $('#subnewtopic').prop('disabled', true);
        // e.preventDefault();
    });
</script>

要记住的事情:

  • POST操作太快,您无法看到已禁用的按钮。取消注释e.preventDefault()以下$("#subnewtopic.prop('disabled', true);以测试其是否有效。
  • 在尝试使用此功能之前必须启用jQuery。
  • 使用Firefox或Chrome的开发者工具检查Javascript控制台是否有任何错误,使用网络标签查看是否发布了任何请求。

除此之外,这应该非常简单。就像我说的那样,我没有错误,你很奇怪,可能是非常简单的事情。如果这有帮助,请告诉我!

答案 1 :(得分:-3)

确保在jquery函数中返回true,否则服务器提交将不会发生 (这是错误检查的情况)

更新:

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

见:
Form Submit Execute Javascript Best Practice?

不确定为什么他在那个答案中回归假,我认为这是真的。试试两个。

相关问题