【发布时间】:2014-12-13 13:09:21
【问题描述】:
我们使用自定义按钮来提交表单。将点击事件分配给 .btn-submit 以提交相应的表单。但是,如果在 <form> 中没有某种类型的 <button type="submit"> 或 <input type="submit"> 元素,则在用户名或密码文本字段中按 ENTER 不会提交表单。
在input 字段中按ENTER 键时,如果<form> 中没有type="submit" 元素,我如何仍然允许用户提交表单?
HTML
<form action="post.php" method="post">
<p><b>Username</b> <input type="text" name="username" style="width: 300px; font-size: 18px"></p>
<p><b>Password</b> <input type="password" name="password" style="width: 300px; font-size: 18px"></p>
<input type="hidden" name="user_login" value="1">
<div class="btn-inline btn-green btn-submit">Log In</div>
</form>
JS
$(document).ready(function()
{
$('.btn-submit').on('click', function(e)
{
$(this).parents('form:first').submit();
});
});
【问题讨论】:
-
您需要捕获回车键按下,最好在表单上使用 jQuery 代理。
-
为什么你不想添加一个按钮(type=submit)?您可以通过 css 使其不可见:
display: none -
查看模仿的答案。它接近你想要的和我会为你提供的。而不是在 preventDefault 之后执行按钮单击元素,只需 form.submit()
标签: javascript jquery html forms