如何使用 jQuery (javascript) 绕过 HTML 表单提交
我有一个简单的表单,
<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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您不想提交表单,可以使用
preventDefault( )
或
return false;
最好选择前者,除非您还想阻止事件冒泡。If you don't want to submit the form, you can prevent the default action using
preventDefault()
or
return false;
It's better to do the former unless you also want to stop the event from bubbling.您可以使用 event.preventDefault() 或
return false;
。然后您可以使用form.submit()
轻松提交表单You can use event.preventDefault() or
return false;
. Then you can easily submit the form withform.submit()
您必须将处理程序添加到表单提交事件,而不是按钮单击。
尝试这样的事情:
You have to add handler to form submit event, not to the button click.
Try something like this: