1

I am using a form and on submit $(document).on('submit','form',function(event){

now I want to stop the form from being submitted to validate. The options I found are

event.preventDefault()
Event.stopPropagation()
return false
throw new Error("Something went badly wrong!");
calling a fake function which does not exist

Would anyone explain which one I should use and are there more methods to stop the execution of Javascript form submission?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
vinayak shahdeo
  • 1,348
  • 2
  • 11
  • 21

1 Answers1

6

The rundown:

  • You can use event.preventDefault() if you only want to prevent the default of the event (in this case, submitting a form).
  • You can use return false (in a jQuery event handler like yours) if you want to both prevent the default and stop propagation of the event to ancestor elements. (Note that that's different from what return false means in native event handling, as I cover in this blog post.)
  • Using event.stopPropagation() (not Event.stopPropagation()) won't prevent the default action at all: the form will still be submitted.
  • Throwing an error from the handler won't prevent the default action of the event.
  • Calling a function that doesn't exist is just throwing an error, see above.
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875