Search code examples
jqueryajaxdouble-submit-prevention

jQuery Disable Enter Key after Enter Key has been hit when Enter key has already been disabled


I have disabled my enter key so that I can do an ajax submission, but I want to make sure that the form isn't submitted twice if the user hits enter twice before the response from the server comes back.

Here I have disabled the enter key and assigned a function to it called 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(); });
});

I tried to bind() again elsewhere, but it didn't do anything. I tried preventDefault() in various places, but I think I'm either putting it in the wrong place, or else that's the wrong thing to do. I can't seem to get this to work.

I found this: How to disable Enter/Return Key After a function is executed because of it?, but it doesn't answer my question because in the poster's example, the script checks to see whether there is anything in the box, but I want to check to see whether I have submitted or not. I'm not sure how to do that. What I would really like to do is disable the enter key until I hear back from the server on the ajax call. Here is 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();
        }
    });
}

I would prefer not to have to do anything on the server-side, because I need this submit functionality to be as fast as possible (this will be a fast paced data entry form).


Solution

  • Make use of a variable like this:

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