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

前端 未结 10 1269
终归单人心
终归单人心 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;
    });
    
    0 讨论(0)
  • 2020-12-08 23:02

    I'm not sure what language/framework you're working with or if it's just straight HTML. But in a Rails app I wrote I pass a data attribute on the form button disable_with which keeps the button from being clickable more than once while the transaction is in process.

    Here's what the ERB looks like.

    <%= f.button "Log In", class: 'btn btn-large btn-block btn-primary', data: {disable_with: "<i class='icon-spinner'></i>Logging In..."} %>
    
    0 讨论(0)
  • 2020-12-08 23:03

    This should do the trick:

    $("form").submit(function() {
       $(":submit", this).attr("disabled", "disabled");
    });
    

    No JQuery?

    Alternatively, you can make a check from db to check if a record already exist and if so, don't insert new one.

    0 讨论(0)
  • 2020-12-08 23:12

    Here is bit of jQuery that I use to avoid the double click problem. It will only allow one click of the submit button.

    $(document).ready(function() {
      $("#submit").on('click', function() {
      });
    });
    
    0 讨论(0)
提交回复
热议问题