Prevent double submission of forms in jQuery

后端 未结 22 1608
旧时难觅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 think Nathan Long's answer is the way to go. For me, I am using client-side validation, so I just added a condition that the form be valid.

    EDIT: If this is not added, the user will never be able to submit the form if the client-side validation encounters an error.

            // jQuery plugin to prevent double submission of forms
            jQuery.fn.preventDoubleSubmission = function () {
                $(this).on('submit', function (e) {
                    var $form = $(this);
    
                    if ($form.data('submitted') === true) {
                        // Previously submitted - don't submit again
                        alert('Form already submitted. Please wait.');
                        e.preventDefault();
                    } else {
                        // Mark it so that the next submit can be ignored
                        // ADDED requirement that form be valid
                        if($form.valid()) {
                            $form.data('submitted', true);
                        }
                    }
                });
    
                // Keep chainability
                return this;
            };
    

提交回复
热议问题