jQuery 使用 Enter 键提交表单而没有提交按钮?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8981637/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 11:21:47  来源:igfitidea点击:

Submit form with Enter key without submit button?

jqueryhtmlformsform-submit

提问by Alex

Possible Duplicate:
HTML: Submitting a form by pressing enter without a submit button

可能的重复:
HTML:在没有提交按钮的情况下按 Enter 提交表单

How can I submit a form with just the Enter key on a text input field, without having to add a submit button?

如何仅使用文本输入字段上的 Enter 键提交表单,而无需添加提交按钮?

I remember this worked in the past, but I tested it now and the form doesn't get submitted unless there's a submit-type input field inside it.

我记得这在过去有效,但我现在对其进行了测试,除非其中有一个提交类型的输入字段,否则表单不会被提交。

回答by timmah.faase

$("input").keypress(function(event) {
    if (event.which == 13) {
        event.preventDefault();
        $("form").submit();
    }
});

回答by Jay Gilford

Change #form to your form's ID

将#form 更改为您表单的 ID

$('#form input').keydown(function(e) {
    if (e.keyCode == 13) {
        $('#form').submit();
    }
});

Or alternatively

或者替代地

$('input').keydown(function(e) {
    if (e.keyCode == 13) {
        $(this).closest('form').submit();
    }
});

回答by Brian Glaz

Jay Gilford's answer will work, but I think really the easiest way is to just slap a display: none;on a submit button in the form.

杰伊吉尔福德的答案会起作用,但我认为最简单的方法是display: none;在表单中的提交按钮上打一个耳光。

回答by FtDRbwLXw6

@JayGuilford's answer is a good one, but if you don't want a JS dependency, you could use a submit element and simply hide it using display: none;.

@JayGuilford 的回答很好,但是如果您不想要 JS 依赖项,则可以使用 submit 元素并简单地使用display: none;.