Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I correctly capture and re-fire the form submit event, guaranteed?

Tags:

This is probably not your usual "How do I capture form submit events?" question.

I'm trying to understand precisely how form submit events are handled by jQuery, vanilla Javascript, and the browser (IE/FF/Chrome/Safari/Opera) -- and the relationships between them. (See my other question.) After hours of Googling and experimenting, I still cannot come to a conclusion, either because of discord or vagueness.

I'm finishing up a script which integrates with website forms so that the forms can't be submitted until an AJAX request comes back.

Ideally:

  1. User fills out form
  2. Form is submitted -- but no previously-bound event handlers are called, except mine
  3. My handler makes an API request (asynchronously, of course)
  4. User confirms validation results from API response
  5. Form submit continues normally, automatically, invoking the other handlers which before were suppressed

My current understanding is that: (these may be wrong, please correct me if so)

  • jQuery binds form submit event handlers to the submit button click events
  • Event handlers directly on the submit element click events (whether in the markup like onclick="" or bound using jQuery) are executed first
  • Event handlers on the form submit events (whether in the markup like onsubmit="" or bound using jQuery) are executed next
  • Calling $('[type=submit]').click() doesn't invoke the form's submit event, so its handlers don't get called
  • Calling $('form').submit() doesn't invoke the submit button's click event, so its handlers don't get called
  • Yet somehow, a user that clicks the submit button ends up invoking handlers bound to the form's submit event... (but as mentioned above, invoking click on the submit button doesn't do the same)
  • In fact, any way the user submits the form (via submit button or hitting Enter), handlers bound with jQuery to the form submit event are called...

Right now, I am:

  1. Unbinding handlers bound with jQuery to the submit button's click event while preserving a reference to them
  2. Binding my own handler to the submit button's click event, so it executes first
  3. Taking any handlers bound in the markup using onclick="" and onsubmit="" (on their respective elements) and re-binding them using jQuery (so they execute after mine), then setting the attributes to null
  4. Re-binding their handlers (from step 1) so they execute last

Actually, this has been remarkably effective in my own testing, so that my event handler fires first (essential).

The problem, and my questions:

My handler fires first, just as expected (so far). The problem is that my handler is asynchronous, so I have to suppress (preventDefault/stopPropagation/etc) the form submit or submit button click event which invoked it... until the API request is done. Then, when the API request comes back, and everything is A-OK, I need to re-invoke the form submit automatically. But because of my observations above, how do I make sure all the event handlers are fired as if it were a natural form submit?

What is the cleanest way to grab all their event handlers, put mine first, then re-invoke the form submit so that everything is called in its proper order?

And what's the difference, if any, between $('form').submit() and $('form')[0].submit()? (And the same for $('[type=submit]').click() and $('[type=submit]')[0].click())

tl;dr, What is the canonical, clear, one-size-fits-all documentation about Javascript/jQuery/browser form-submit-event-handling? (I'm not looking for book recommendations.)


Some explanation: I'm trying to compensate for a lot of the Javascript in shopping cart checkout pages, where sometimes the form is submitted only when the user CLICKS the BUTTON (not a submit button) at the bottom of the page, or there are other tricky scenarios. So far, it's been fairly successful, it's just re-invoking the submit that's really the problem.

like image 914
Matt Avatar asked Oct 19 '12 16:10

Matt


2 Answers

Bind to the form's submit handler with jQuery and prevent the default action, then, when you want to submit the form, trigger it directly on the form node.

$("#formid").submit(function(e){
    // prevent submit
    e.preventDefault();

    // validate and do whatever else


    // ...


    // Now when you want to submit the form and bypass the jQuery-bound event, use 
    $("#formid")[0].submit();
    // or this.submit(); if `this` is the form node.

});

By calling the submit method of the form node, the browser does the form submit without triggering jQuery's submit handler.

like image 86
Kevin B Avatar answered Sep 19 '22 14:09

Kevin B


These two functions might help you bind event handlers at the front of the jquery queue. You'll still need to strip inline event handlers (onclick, onsubmit) and re-bind them using jQuery.

// prepends an event handler to the callback queue
$.fn.bindBefore = function(type, fn) {

    type = type.split(/\s+/);

    this.each(function() {
        var len = type.length;
        while( len-- ) {
            $(this).bind(type[len], fn);

            var evt = $.data(this, 'events')[type[len]];
            evt.splice(0, 0, evt.pop());
        }
    });
};

// prepends an event handler to the callback queue
// self-destructs after it's called the first time (see jQuery's .one())
$.fn.oneBefore = function(type, fn) {

    type = type.split(/\s+/);

    this.each(function() {
        var len = type.length;
        while( len-- ) {
            $(this).one(type[len], fn);

            var evt = $.data(this, 'events')[type[len]];
            evt.splice(0, 0, evt.pop());
        }
    });
};

Bind the submit handler that performs the ajax call:

$form.bindBefore('submit', function(event) {
    if (!$form.hasClass('allow-submit')) {
        event.preventDefault();
        event.stopPropagation();
        event.stopImmediatePropagation();

        // perform your ajax call to validate/whatever
        var deferred = $.ajax(...);
        deferred.done(function() {
            $form.addClass('allow-submit');
        });

        return false;
    } else {
        // the submit event will proceed normally
    }
});

Bind a separate handler to block click events on [type="submit"] until you're ready:

$form.find('[type="submit"]').bindBefore('click', function(event) {
    if (!$form.hasClass('allow-submit')) {
        // block all handlers in this queue
        event.preventDefault();
        event.stopPropagation();
        event.stopImmediatePropagation();
        return false;
    } else {
        // the click event will proceed normally
    }
});
like image 22
colllin Avatar answered Sep 18 '22 14:09

colllin