使用Javascript和Prototype阻止多个提交

时间:2012-06-13 09:41:48

标签: javascript html forms prototypejs

我尝试使用Javascript通过Prototype API阻止HTML表单中的多个提交。以下是我用来解决此问题的代码段:

function preventMultipleSubmits() {
    this.select('input[type="submit"]').invoke('disable');
    return true;
}

document.observe('dom:loaded', function() {
    var forms = $A(document.getElementsByTagName('form'));
    forms.each(function(form) {
        form.observe('submit', preventMultipleSubmits)
    });
});

该代码段的问题在于提交表单不再调用服务器端。我知道IE浏览器并不能很好地支持CCS选择器,但问题也与Firefox有关,我想首先关注FF。

环境和工具:

  • Firefox 13.0
  • Prototype 1.6.1

1 个答案:

答案 0 :(得分:1)

this.select('input[type="submit"]').invoke('disable');

这似乎只是将已禁用的属性添加到submit按钮。您仍然可以通过输入提交单字段表单。

您可以尝试这样的事情:

<script type="text/javascript">
function preventMultipleSubmits(event) {
    if (this.hasClassName('allow-one-time-submit')) {
        this.removeClassName('allow-one-time-submit');
        // don't stop the event
    } else {
        alert('You already submitted');
        event.stop();
    }
}

document.observe('dom:loaded', function() {
    var forms = $A(document.getElementsByTagName('form'));
    forms.each(function(form) {
        // add Class Name to each and every form on load
        form.addClassName('allow-one-time-submit');
        form.observe('submit', preventMultipleSubmits)
    });

});
</script>


<form action="http://www.example.com/path/to/action" class="allow-one-time-submit">
    <input type="text">
    <input type="submit" value="Submit">
</form>