Barka
Barka

Reputation: 8932

preventing the default form submit event from firing if javascript is anabled using jquery

I have a form on a page. Inside it I have an element. If javascript is on, I want to disable the submit event. And handle the action in MyMethod using Ajax. How do I prevent the submit event from firing?

I believe something of the form: event.preventDefault() would do the trick. But I cant figure out how to pass in the event.

Thanks!

Upvotes: 1

Views: 72

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039468

You could subscribe to the .submit() event of the form and return false from it:

$(function() {
    $('form').submit(function() {
        // TODO: do your AJAX stuff here
        // for example ajaxify the form
        $.ajax({
            url: this.action,
            type: this.method,
            data: $(this).serialize(),
            success: function(result) {
                // TODO: process the result of your AJAX request
            }
        });

        // this is what will cancel the default action
        return false;
    });
});

or:

$(function() {
    $('form').submit(function(evt) {
        evt.preventDefault();

        // TODO: do your AJAX stuff here
        // for example ajaxify the form
        $.ajax({
            url: this.action,
            type: this.method,
            data: $(this).serialize(),
            success: function(result) {
                // TODO: process the result of your AJAX request
            }
        });
    });
});

Upvotes: 3

Related Questions