How can I prevent a double submit with jQuery or Javascript?

前端 未结 10 1313
终归单人心
终归单人心 2020-12-08 22:44

I keep getting duplicate entries in my database because of impatient users clicking the submit button multiple times.

I googled and googled and found a few scripts,

10条回答
  •  余生分开走
    2020-12-08 22:58

    If you are using client-side validation and want to allow additional submit attempts if the data is invalid, you can disallow submits only when the form content is unchanged:

    var submittedFormContent = null;
    $('#myForm').submit(function (e) {
        var newFormContent = $(this).serialize();
        if (submittedFormContent === newFormContent)
            e.preventDefault(true);
        else 
            submittedFormContent = newFormContent;
    });
    

提交回复
热议问题