Html 当 textarea 具有焦点时,如何在输入时提交表单?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4418819/
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-29 05:41:14  来源:igfitidea点击:

How to submit a form on enter when the textarea has focus?

htmlforms

提问by andrew

When filling out a form's textarea, the default behavior when the enter key is hit is to move to the next line. How can I change the behavior of the form so it will submit upon user hitting enter even when the user is in a textarea?

填写表单的文本区域时,按下回车键时的默认行为是移动到下一行。如何更改表单的行为,以便即使用户在 textarea 中,它也会在用户点击 Enter 时提交?

I used Firebug to checkout Stack Overflow's comment textarea (which has this behaviour), but couldn't see any JavaScript that achieved this affect. Is there a way to change the behavior of the textarea without using JavaScript?

我使用 Firebug 来检查 Stack Overflow 的注释 textarea(它具有这种行为),但看不到任何实现这种影响的 JavaScript。有没有办法在不使用 JavaScript 的情况下改变 textarea 的行为?

回答by BalusC

You can't do this without JavaScript. Stackoverflow is using the jQueryJavaScript library which attachs functions to HTML elements on page load.

如果没有 JavaScript,您就无法做到这一点。Stackoverflow 使用jQueryJavaScript 库,它在页面加载时将函数附加到 HTML 元素。

Here's how you could do it with vanilla JavaScript:

以下是使用普通 JavaScript 的方法:

<textarea onkeydown="if (event.keyCode == 13) { this.form.submit(); return false; }"></textarea>

Keycode 13 is the enter key.

键码 13 是回车键。

Here's how you could do it with jQuery like as Stackoverflow does:

以下是您可以像 Stackoverflow 一样使用 jQuery 来实现的方法:

<textarea class="commentarea"></textarea>

with

$(document).ready(function() {
    $('.commentarea').keydown(function(event) {
        if (event.which == 13) {
            this.form.submit();
            event.preventDefault();
         }
    });
});

回答by Eric Fortis

<form id="myform">
    <input type="textbox" id="field"/>
    <input type="button" value="submit">
</form>

<script>
    $(function () {
        $("#field").keyup(function (event) {
            if (event.which === 13) {
                document.myform.submit();
            }
        }
    });
</script>

回答by jthompson

Why do you want a textarea to submit when you hit enter?

为什么要在按 Enter 键时提交 textarea ?

A "text" input will submit by default when you press enter. It is a single line input.

当您按 Enter 键时,默认情况下将提交“文本”输入。它是单行输入。

<input type="text" value="...">

A "textarea" will not, as it benefits from multi-line capabilities. Submitting on enter takes away some of this benefit.

“textarea”不会,因为它受益于多行功能。在输入时提交会带走一些这种好处。

<textarea name="area"></textarea>

You can add JavaScript code to detect the enter keypress and auto-submit, but you may be better off using a text input.

您可以添加 JavaScript 代码来检测输入按键和自动提交,但最好使用文本输入。