How to prevent form from being submitted?

Nathan Osman picture Nathan Osman · Jul 28, 2010 · Viewed 443.5k times · Source

I have a form that has a submit button in it somewhere.

However, I would like to somehow 'catch' the submit event and prevent it from occurring.

Is there some way I can do this?

I can't modify the submit button, because it's part of a custom control.

Answer

Ben Rowe picture Ben Rowe · Jul 28, 2010

Unlike the other answers, return false is only part of the answer. Consider the scenario in which a JS error occurs prior to the return statement...

html

<form onsubmit="return mySubmitFunction(event)">
  ...
</form>

script

function mySubmitFunction()
{
  someBug()
  return false;
}

returning false here won't be executed and the form will be submitted either way. You should also call preventDefault to prevent the default form action for Ajax form submissions.

function mySubmitFunction(e) {
  e.preventDefault();
  someBug();
  return false;
}

In this case, even with the bug the form won't submit!

Alternatively, a try...catch block could be used.

function mySubmit(e) { 
  e.preventDefault(); 
  try {
   someBug();
  } catch (e) {
   throw new Error(e.message);
  }
  return false;
}