且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何防止表单被提交?

更新时间:2023-12-01 22:14:58

与其他答案不同,返回 false 只是答案的部分。考虑在返回语句之前出现JS错误的情况...



html
 < form onsubmit =return mySubmitFunction()> 
...
< / form>

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

返回 false 此处将不会被执行,表单将以任何方式提交。您还应该调用 preventDefault 来防止Ajax表单提交的默认表单操作。

  function mySubmitFunction(evt){
evt.preventDefault();
someBug();
返回false;
}

在这种情况下,即使有错误,表单也不会提交!



或者,可以使用 try ... catch 块。

  function mySubmit(evt){
evt.preventDefault();
尝试{
someBug();
} catch(e){
throw new Error(e.message);
}
返回false;
}


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.

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()">
  ...
</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(evt) {
  evt.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(evt) { 
  evt.preventDefault(); 
  try {
   someBug();
  } catch (e) {
   throw new Error(e.message);
  }
  return false;
}