Javascript 如何禁用文本区域上的 ENTER 键?

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

How can I disable the ENTER key on my textarea?

javascriptjqueryeventstextarea

提问by faq

<form name='qform'>
<textarea name='q' rows='3' cols='60' wrap='hard' id='q' onkeydown="if (event.keyCode == 13) document.getElementById('clickit').click()"></textarea>
<input type='button' value='search' id='clickit' onclick="get();">
</form>

I have this form... it doesn't have a submit button because I am using jquery and under this form is a div area where the results will be shown. It is a search engine that does not have an input box but instead has a textarea. This is because it will be a multiple word searcher.

我有这个表单...它没有提交按钮,因为我使用的是 jquery,并且在这个表单下是一个 div 区域,其中将显示结果。它是一个没有输入框但有一个文本区域的搜索引擎。这是因为它将是一个多词搜索器。

The problem is that if I press enter, the query is submitted and everything is ok ... but the focus on textarea goes down one line and that is a problem for me.

问题是,如果我按回车键,则提交查询并且一切正常……但是对 textarea 的关注下降了一行,这对我来说是个问题。

Basically I want the enter to have that one function only(submit) end nothing else.

基本上我希望输入只有一个功能(提交)结束。

采纳答案by Null Head

In the jquery function, use event.preventdefault and next do what you like. For example

在 jquery 函数中,使用 event.preventdefault 并下一步做你喜欢的。例如

<script>
$("a").click(function(event) {
  event.preventDefault();
//Do your logic here
});
</script>

http://api.jquery.com/event.preventDefault/

http://api.jquery.com/event.preventDefault/

回答by alpc

$(document).ready(function() {

    $('textarea').keypress(function(event) {

        if (event.keyCode == 13) {
            event.preventDefault();
        }
    });
});

回答by Michael Mior

Why not just use <input type="text">if you don't want multiple lines? You mentioned it will be a "multiple word searcher". Why does this require a <textarea>?

<input type="text">如果您不想要多行,为什么不直接使用?您提到它将是一个“多词搜索器”。为什么这需要一个<textarea>

Update

更新

Try this

尝试这个

$('textarea').bind('keypress', function(e) {
  if ((e.keyCode || e.which) == 13) {
    $(this).parents('form').submit();
    return false;
  }
});