如何防止表单被提交? [英] How to prevent form from being submitted?

查看:127
本文介绍了如何防止表单被提交?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



然而,我想以某种方式'抓住'提交事件并阻止它发生。

我有一个表单,它有一个提交按钮。



有没有办法可以做到这一点?

我无法修改提交按钮,因为它是部分自定义控件。

解决方案

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



html

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

脚本
< pre $ 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;
}

这篇关于如何防止表单被提交?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆