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.
Cancel using event.preventDefault() method.
1234$('form').submit(submit_handler1);function submit_handler1(event) {event.preventDefault();}Cancel by returning false from the submit handler.
1234$('form').submit(submit_handler2);function submit_handler2() {return false;}Cancel by returning false from the submit handler.
1234$('form').submit(submit_handler3);submit_handler3 = function () {return false;}Cancel by returning false from the submit handler.
1234$('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.
Author: Deepu Mohan Puthrote
Link: https://deepumohan.com/tech/cancel-form-submit-when-using/
This work by Deepu Mohan Puthrote is licensed under a Creative Commons Attribution 4.0 International License