jquerydouble-submit-problem

Prevent jQuery dialog submitting twice


I would like to prevent user from submitting dialog form twice.

Here is my submit code:

$('form', dialog).submit(function () {
    if (dialogSubmitted) { return false; }
    dialogSubmitted = true;
    ...
    ...
});

Where dialogSubmitted is a variable indicating if the form is already submitted. The problem is that it doesn't work. When I open the dialog and I press Enter twice (quickly) the form is submitted twice.

Any idea?

Thanks.


UPDATE

Here is another attempt which also failed when I press enter key twice very quickly:

    $('form', dialog).one('submit', function (evt) {

        evt.preventDefault();

        $(this).on('submit', function (evt) {
            evt.preventDefault();
        });

        $.post($(this).attr('action'), $(this).serialize(), function (data, status) {
            $('#my-modal').modal('hide');
            ...
            ...
        }).error(function (error, status, a, b) {
            $('.modal-body p.body').html(error.responseText);
            writeError('msgError', pStopIndex.validationFailed);
        });

        // Unbind form submitting
        $('form', dialog).unbind();
        return false;
    });

As you can see, I do ajax post (in place of classic form submit). Maybe the problem is there?

Here is the capture of traces from Google Chrome:

enter image description here

We can see there are 2 posts. Only occurrs when I press enter key twice quickly or click submit button twice quickly.

Any idea? Thanks.


Solution

  • just use one() method

    see example fiddle : http://jsfiddle.net/MpBCL/

    $('form', dialog).one('submit', function (evt) {
    
        /* prevent default action */
        evt.preventDefault();
    
        ...
        /* code to be executed once */
        ...
    
        /**
         * disable default action (this handler will be attached after first 
         * submit event and it will prevent any further submit action
         */
        $(this).on('submit', function (evt) {
           evt.preventDefault();
        });
    
    });
    

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

    Description: Attach a handler to an event for the elements. The handler is executed at most once per element.