如何使用 jQuery (javascript) 绕过 HTML 表单提交

发布于 2024-12-08 23:27:10 字数 650 浏览 1 评论 0原文

我有一个简单的表单,

<form action="try.php" method="POST">
    <input id="name" name="name" type="text" placeholder="Name" />
    <input id="btn" name="" type="submit" value="Submit" />
</form>

当我单击提交按钮时,我只想在满足特定条件时提交表单;如果没有,则不会提交表单(而是显示并提醒)。 我不想更改此处的标记。那么,如何确保即使我提供了

,如果条件满足,表单也不会提交没有兑现吗?

我想做类似下面代码的事情。

//jQuery code   
$("#btn").live('click', function(event) {
      if(<condition is true>){
          //Show message
      } else {
         //Submit Form
      }
});

I've a simple form

<form action="try.php" method="POST">
    <input id="name" name="name" type="text" placeholder="Name" />
    <input id="btn" name="" type="submit" value="Submit" />
</form>

When I click the submit button, I want to submit the form only if a certain condition is met; and if not, the form will not be submitted (instead show and alert). I do not want to change the markup here. So how do I make it sure that, even though I've provided <form action="try.php" method="POST">, the form doesn't get submitted if the condition is not fulfilled?

I want to do something like the code below.

//jQuery code   
$("#btn").live('click', function(event) {
      if(<condition is true>){
          //Show message
      } else {
         //Submit Form
      }
});

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

妄司 2024-12-15 23:27:10

如果您不想提交表单,可以使用 preventDefault( )

if(<condition is true>){
      event.preventDefault(); 
  }

return false; 最好选择前者,除非您还想阻止事件冒泡。

If you don't want to submit the form, you can prevent the default action using preventDefault()

if(<condition is true>){
      event.preventDefault(); 
  }

or return false; It's better to do the former unless you also want to stop the event from bubbling.

雅心素梦 2024-12-15 23:27:10

您可以使用 event.preventDefault()return false;。然后您可以使用 form.submit() 轻松提交表单

You can use event.preventDefault() or return false;. Then you can easily submit the form with form.submit()

夜访吸血鬼 2024-12-15 23:27:10

您必须将处理程序添加到表单提交事件,而不是按钮单击。

尝试这样的事情:

$('#form').submit(function() {
  if(<condition is true>) {
    alert('Fill all fields');
    return false; // will cancel default submit
  }

  // do something before submit
  // if necessary
});

You have to add handler to form submit event, not to the button click.

Try something like this:

$('#form').submit(function() {
  if(<condition is true>) {
    alert('Fill all fields');
    return false; // will cancel default submit
  }

  // do something before submit
  // if necessary
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文