我们使用自定义按钮来提交表单。单击事件被分配给 .btn-submit 以提交相应的表单。但是,没有某种类型的 <button type="submit">
或<input type="submit">
元素位于<form>
内,在用户名或密码文本字段中按 ENTER 不会提交表单。
如何在 input
中按 ENTER 键时仍允许用户提交表单没有 type="submit"
的字段<form>
中存在的元素?
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();
});
});
最佳答案
你可以这样做,这样当在输入中按下回车键时,它就会激活提交按钮
$('form').keypress(function(e){
var code = e.keyCode || e.which;
if( code === 13 ) {
e.preventDefault();
$( ".btn-submit" ).click();
};
});
编辑
如果在 textarea
中按回车键,则不会导致单击提交按钮。它只会对 input
执行此操作text
类型的 s现在。
$('input:text').keypress(function(e){
var code = e.keyCode || e.which;
if( code === 13 ) {
e.preventDefault();
$( ".btn-submit" ).click();
};
});
关于javascript - 当不存在类型 ="submit"元素时,表单不会在 ENTER 上提交,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26433677/