【问题标题】:jQuery Disable Enter Key after Enter Key has been hit when Enter key has already been disabledjQuery Disable Enter Key after Enter Key has been hit when Enter key has been disabled
【发布时间】:2011-09-27 16:43:15
【问题描述】:

我已禁用我的 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(),但我认为我要么把它放在错误的地方,要么这是错误的做法。我似乎无法让它工作。

我找到了这个:How to disable Enter/Return Key After a function is executed because of 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();
        }
    });
}

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

【问题讨论】:

    标签: jquery ajax double-submit-prevention


    【解决方案1】:

    使用这样的变量:

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • 这是一个很好的观点,这就是我所做的,实际上$("#submit") 只是一个按钮。但是$('#hidden') 是提交。我留下提交的原因是因为对于不完整的表单,我使用非 ajax 服务器端脚本在警报发生后用消息/建议标记坏控件。
      • 我不明白你为什么需要一个提交按钮。
      猜你喜欢
      • 2012-09-19
      • 2014-10-27
      • 1970-01-01
      • 1970-01-01
      • 2011-05-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多