Sponsored Link

Sunday, August 21, 2011

Cancel html form submission when using jQuery.submit()

Most web developers might have come across this scenario - cancel the form submission after it is fired. This happens when form validation is fired on the submit event of form element. You may have to cancel the submission based on the validation.

This post is on how to cancel an html form submission when using jQuery. The following 4 code snippets does the same the job. This can be used to prevent submit event being fired based on some validation.

1. Cancel using event.preventDefault() method.
$('form').submit(submit_handler1);

function submit_handler1(event) {
  event.preventDefault();
}

2. Cancel by returning false from the submit handler.
$('form').submit(submit_handler2);

function submit_handler2() {
 return false;
}

3. Cancel by returning false from the submit handler.
$('form').submit(submit_handler3);

submit_handler3 = function () {
 return false;
}

4. Cancel by returning false from the submit handler.
$('form').submit(submit_handler4);

$.submit_handler4 = function () {
 return false;
}

In these examples I have used a submit handler function. It is always better to write submit handler function separately, for code maintainability. Here examples 2, 3 and 4 are same only difference is in the way submit handler function is attached to the submit event.

To learn/improve jQuery skills, buy one of these book from Amazon.com.

Related Posts Plugin for WordPress, Blogger...