Prevent double submission of forms in jQuery

后端 未结 22 1765
旧时难觅i
旧时难觅i 2020-11-22 08:10

I have a form that takes a little while for the server to process. I need to ensure that the user waits and does not attempt to resubmit the form by clicking the button agai

22条回答
  •  忘掉有多难
    2020-11-22 08:36

    I've been having similar issues and my solution(s) are as follows.

    If you don't have any client side validation then you can simply use the jquery one() method as documented here.

    http://api.jquery.com/one/

    This disables the handler after its been invoked.

    $("#mysavebuttonid").on("click", function () {
      $('form').submit();
    });
    

    If you're doing client side validation as I was doing then its slightly more tricky. The above example would not let you submit again after failed validation. Try this approach instead

    $("#mysavebuttonid").on("click", function (event) {
      $('form').submit();
      if (boolFormPassedClientSideValidation) {
            //form has passed client side validation and is going to be saved
            //now disable this button from future presses
            $(this).off(event);
       }
    });
    

提交回复
热议问题