Javascript 在 ENTER 上提交文本框

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

Javascript submit textbox on ENTER

javascriptsubmitenter

提问by harisdev

Possible Duplicate:
Bind textbox to 'enter' key

可能的重复:将
文本框绑定到“输入”键

I've made ajax / jquery chat and there is no form in textbox for message , so i can't submit that message with ENTER on keyboard.Is there any way to submit that value from textbox with javascript ?

我已经进行了 ajax/jquery 聊天,但文本框中没有用于消息的表单,所以我无法使用键盘上的 ENTER 提交该消息。有什么方法可以使用 javascript 从文本框中提交该值?

Thanks.

谢谢。

回答by

document.getElementById("id_of_your_textbox").addEventListener("keydown", function(e) {
    if (!e) { var e = window.event; }
    e.preventDefault(); // sometimes useful

    // Enter is pressed
    if (e.keyCode == 13) { submitFunction(); }
}, false);

回答by nachito

$('#textboxId').keydown(function (event) {
    var keypressed = event.keyCode || event.which;
    if (keypressed == 13) {
        $(this).closest('form').submit();
    }
});

If you don't have form, then replace $(this).closest('form').submit();with whatever AJAX/submit logic you have.

如果您没有表单,则用您$(this).closest('form').submit();拥有的任何 AJAX/提交逻辑替换。

回答by moranjk

You will need to listen for the ENTER key press event. Take a look at Enter key press event in JavaScriptfor some examples on how it is done.

您将需要监听 ENTER 键按下事件。查看JavaScript中的Enter 按键事件,了解有关如何完成的一些示例。