阻止表单提交
我试图使用 jQuery 阻止在某个文本区域未填充时提交表单。但是,如果数据已在数据库中,则不需要填充文本区域。我正在使用以下代码,但 jquery 似乎不正确。
HTML 和PHP:
<form id="form" action="page1.php" method="post">
<input type="textarea" name="name1" placeholder="<?= empty($val1)? 'Enter your val here': $val1 ?>" />
<p class="submit">
<input type="submit" value="Go!" />
</p>
</form>
<div id="log"></div>
JavaScript:
$("#form[input[placeholder='Enter your val here']]").submit(function(event) {
event.preventDefault();
$('<div/>')
.append('please enter the val first')
.appendTo('#log');
});
};
I'm trying to prevent a form from submitting if a certain textarea is not filled, using jQuery. However, the textarea doesn't need to be filled if the data is already in the database. I am using the following code, but the jquery does not seem to be correct.
HTML & PHP:
<form id="form" action="page1.php" method="post">
<input type="textarea" name="name1" placeholder="<?= empty($val1)? 'Enter your val here': $val1 ?>" />
<p class="submit">
<input type="submit" value="Go!" />
</p>
</form>
<div id="log"></div>
Javascript:
$("#form[input[placeholder='Enter your val here']]").submit(function(event) {
event.preventDefault();
$('<div/>')
.append('please enter the val first')
.appendTo('#log');
});
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您尝试绑定到表单的
onsubmit
事件,您的选择器似乎有点偏离。现在你的选择器的结果可能什么也没有,因为它是一个无效的选择器。您可能试图这样做:但实际上,您所需要的是:
上面的逻辑是这样的,如果出现以下情况,表单将不会提交:
在所有其他情况下,表单 将不会提交将提交,因为:
Your selector seems a bit off if you're trying to bind to the form's
onsubmit
event. The result of your selector now is probably nothing because it's an invalid selector. You were probably trying to do:But really, all you need is:
The logic above is such that the form will NOT submit if:
In all other cases, the form will submit, because:
在文本上放置一个类,以便您知道是否需要填写:
并检查该字段是否为空且为必填:(
请原谅任何语法错误......这只是为了提供它的一般要点.)
此外,请考虑禁用提交按钮并始终显示消息,直到表单有效并准备好提交为止。我认为这对用户更加友好。
Put a class on the textare so you'll know if it needs to be filled in or not:
And check if the field is empty and required:
(Please excuse any syntax errors... This is just to provide the general gist of it.)
Additionally, consider disabling the submit button and showing the message all the time until the form is valid and ready for submission. That would be more user friendly in my opinion.
每当您不想提交时,只需
return false;
Simply
return false;
whenever you don't want to submit