jQuery禁用Enter键,当Enter键已经禁用时,按下Enter键后禁用Enter键



我已经禁用了enter键,这样我就可以进行ajax提交,但是我想确保如果用户在服务器返回响应之前点击两次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()在不同的地方,但我认为我要么把它放在错误的地方,否则这是错误的事情。我似乎不能使这个工作。

我发现这个:如何禁用输入/返回键后,一个功能被执行,因为它?,但是它没有回答我的问题,因为在海报的例子中,脚本检查是否有任何东西在盒子里,但我想检查我是否已经提交。我不知道该怎么做。我真正想做的是禁用回车键,直到我从服务器收到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();
        }
    });
}

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

使用如下变量:

$(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(); 
        }
    });
});

submit按钮更改为常规按钮并使用onclick事件使用JavaScript提交表单更容易。这样按回车键就没有任何作用了。在单击按钮时禁用该按钮,并在Ajax调用成功时启用该按钮。

最新更新