2011-09-27 171 views
1

我禁用了我的输入密钥,以便我可以做一个ajax提交,但我想确保表单没有提交两次if在来自服务器的响应返回之前,用户输入两次。jQuery在输入密钥已被禁用时,输入密钥已被命中后禁用输入密钥

在这里,我已经禁用回车键和分配功能,把它称为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(); 
     } 
    }); 
} 

我宁愿不必须做对服务器端的什么,因为我需要这个提交功能,以便尽可能快(这将是一个快节奏的数据输入窗体)。

回答

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

}); 
0

它更容易只是改变你的提交按钮,你定期按钮的使用onclick事件提交使用JavaScript形式。这样按下输入什么都不做。单击时禁用该按钮,并在Ajax调用成功时启用该按钮。

+0

这是一个很好的点,这就是我所做的事情,其实'$(“#提交”)'只是一个按钮。但'$('#hidden')'是一个提交。我离开提交的原因是因为对于不完整的表单,在警报发生后,我使用非ajax服务器端脚本来标记带有消息/建议的错误控件。 – tjb1982

+0

我不明白你为什么需要一个提交按钮。 –