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

前端 未结 10 1301
终归单人心
终归单人心 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:57

    This is what I came up with in https://github.com/liberapay/liberapay.com/pull/875:

    $('form').on('submit', function (e) {
        var $form = $(this);
        // Check that the form hasn't already been submitted
        if ($form.data('js-submit-disable')) {
            e.preventDefault();
            return false;
        }
        // Prevent submitting again
        $form.data('js-submit-disable', true);
        // Set a timer to disable inputs for visual feedback
        var $inputs = $form.find(':not(:disabled)');
        setTimeout(function () { $inputs.prop('disabled', true); }, 100);
        // Unlock if the user comes back to the page
        $(window).on('focus pageshow', function () {
            $form.data('js-submit-disable', false);
            $inputs.prop('disabled', false);
        });
    });
    

提交回复
热议问题