Intercept a form submit with jQuery and prevent or allow submission

Goal: Intercept a form submit, find out what submit button was clicked/invoked and decide to prevent the submission or continue to submit.

Solution:
$(document).ready(function() {
    $("form").submit(function(e) {
        if (e.originalEvent.explicitOriginalTarget.id == "myButton") {
            if (some status is true continue to submit the form)
                return true;
                //If the status above is false continue to prompt the user if they want to submit or not
            var ok = confirm('Do you really want to save your data?');
            if (ok) {               
                return true;
            }
            else {
                //Prevent the submit event and remain on the screen
                e.preventDefault();
                return false;
            }
        }
    });

    return;
});

Print | posted @ Wednesday, September 09, 2009 10:33 AM

Comments on this entry:

Gravatar # re: Intercept a form submit with jQuery and prevent or allow submission
by iririr at 10/14/2009 5:35 PM

Thanks for this, it really helped me out...couldn't find it anywhere else.
Gravatar # re: Intercept a form submit with jQuery and prevent or allow submission
by emi at 10/19/2009 10:31 AM

Thanks a lot!! This is the only page I've found with the trick e.originalEvent.explicitOriginalTarget . Very useful!!
Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification: