1

我已经禁用了我的 enter 键,以便我可以进行 ajax 提交,但我想确保如果用户在服务器的响应返回之前两次点击 enter,则表单不会提交两次。

在这里,我禁用了 enter 键并为其分配了一个名为submitForm()

$(document).ready(function(){
    offset = $("#quantity").html();
    $("#lastName").focus();
    $(document).bind("keypress" , function(e){
        if (e.which == 13 && (!$("#notes").is(":focus")) && (!$("#submit").is(":focus"))) {
            submitForm(); return false;
        }
    })
    $("#submit").click(function(){ submitForm(); });
});

我试图在bind()其他地方再次,但它没有做任何事情。我在不同的地方尝试过preventDefault(),但我认为我要么把它放在错误的地方,要么这样做是错误的。我似乎无法让它工作。

我发现了这个:How to disable Enter/Return Key After a function is executed because it? ,但它没有回答我的问题,因为在发布者的示例中,脚本会检查框中是否有任何内容,但我想检查我是否已提交。我不知道该怎么做。我真正想做的是禁用回车键,直到我收到服务器对 ajax 调用的回复。这是 submitForm():

function submitForm() {
    $.post("/ajax/files" , $("#files").serialize(), function(data){
        filesReset();
        if (data != "") {
            $("#lastInsert table tbody:last").prepend(data);
            $("#lastInsert table tbody:last tr:first").find("td").hide();
            $("#lastInsert table tbody:last tr:first").find("td").fadeIn(1000);
            $("#lastInsert table tbody:last tr:first").effect("highlight" , {"color": "aqua"}, 1000);

            $("#lastInsert table tbody:last tr:last").remove();
        } else {
            alert("Insert rejected: either insufficient criteria or the server is down.");
            $("#hidden").click();
        }
    });
}

我宁愿不必在服务器端做任何事情,因为我需要这个提交功能尽可能快(这将是一个快节奏的数据输入表单)。

4

2 回答 2

3

使用这样的变量:

$(function(){

    var running = false;

    $(document).bind("keypress" , function(e){
        if (e.which == 13) {
            if(running === false) {
                running = true;
                submitForm();
            }
            return false;
        }
    })

    $("#submit").click(function(){
        if(running === false) {
            running = true;
            submitForm(); 
        }
    });

});
于 2011-09-27T16:57:30.533 回答
0

将提交按钮更改为常规按钮并使用 onclick 事件使用 JavaScript 提交表单会更容易。这样按回车键什么都不做。单击时禁用该按钮,并在您的 Ajax 调用成功时启用它。

于 2011-09-27T16:49:23.987 回答