Javascript 如何捕获 Enter 按键?

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

How to capture Enter key press?

javascripttextboxkeypressdom-eventsonkeypress

提问by Joe Yan

In my HTML page, I had a textbox for user to input keyword for searching. When they click the search button, the JavaScript function will generate a URL and run in new window.

在我的 HTML 页面中,我有一个文本框供用户输入关键字进行搜索。当他们单击搜索按钮时,JavaScript 函数将生成一个 URL 并在新窗口中运行。

The JavaScript function work properly when the user clicks the search button by mouse, but there is no response when the user presses the ENTER key.

当用户通过鼠标点击搜索按钮时,JavaScript 功能正常工作,但当用户按下 ENTER 键时没有响应。

function searching(){
    var keywordsStr = document.getElementById('keywords').value;
    var cmd ="http://XXX/advancedsearch_result.asp?language=ENG&+"+ encodeURI(keywordsStr) + "&x=11&y=4";
    window.location = cmd;
}
<form name="form1" method="get">
    <input name="keywords" type="text" id="keywords" size="50" >
    <input type="submit" name="btn_search" id="btn_search" value="Search" 
        onClick="javascript:searching(); return false;" onKeyPress="javascript:searching(); return false;">
    <input type="reset" name="btn_reset" id="btn_reset" value="Reset">
</form>

回答by TryingToImprove

Form approach

形式方法

As scoota269 says, you should use onSubmitinstead, cause pressing enter on a textbox will most likey trigger a form submit (if inside a form)

正如 scoota269 所说,您应该onSubmit改用,因为在文本框上按 Enter 键很可能会触发表单提交(如果在表单内)

<form action="#" onsubmit="handle">
    <input type="text" name="txt" />
</form>

<script>
    function handle(e){
        e.preventDefault(); // Otherwise the form will be submitted

        alert("FORM WAS SUBMITTED");
    }
</script>

Textbox approach

文本框方法

If you want to have an event on the input-field then you need to make sure your handle()will return false, otherwise the form will get submitted.

如果你想在输入字段上有一个事件,那么你需要确保你handle()将返回 false,否则表单将被提交。

<form action="#">
    <input type="text" name="txt" onkeypress="handle(event)" />
</form>

<script>
    function handle(e){
        if(e.keyCode === 13){
            e.preventDefault(); // Ensure it is only this code that rusn

            alert("Enter was pressed was presses");
        }
    }
</script>

回答by bipen

Use onkeypress. Check if the pressed key is enter (keyCode = 13). if yes, call the searching()function.

使用onkeypress. 检查按下的键是否被输入(keyCode = 13)。如果是,则调用该searching()函数。

HTML

HTML

<input name="keywords" type="text" id="keywords" size="50"  onkeypress="handleKeyPress(event)">

JAVASCRIPT

爪哇脚本

function handleKeyPress(e){
 var key=e.keyCode || e.which;
  if (key==13){
     searching();
  }
}

Here is a snippet showing it in action:

这是一个片段,显示它在行动:

document.getElementById("msg1").innerHTML = "Default";
function handle(e){
 document.getElementById("msg1").innerHTML = "Trigger";
 var key=e.keyCode || e.which;
  if (key==13){
     document.getElementById("msg1").innerHTML = "HELLO!";
  }
}
<input type="text" name="box22" value="please" onkeypress="handle(event)"/>
<div id="msg1"></div>

回答by Rahul Dadhich

Try this....

尝试这个....

HTML inline

HTML 内联

onKeydown="Javascript: if (event.keyCode==13) fnsearch();"
or
onkeypress="Javascript: if (event.keyCode==13) fnsearch();"

JavaScript

JavaScript

<script>
function fnsearch()
{
   alert('you press enter');
}
</script>

回答by user2753926

You can use javascript

你可以使用javascript

ctl.attachEvent('onkeydown', function(event) {

        try {
            if (event.keyCode == 13) {
                FieldValueChanged(ctl.id, ctl.value);
            }
            false;
        } catch (e) { };
        return true
    })

回答by Andy - CodeRemedy

Small bit of generic jQuery for you..

一小部分通用 jQuery 为您服务..

$('div.search-box input[type=text]').on('keydown', function (e) {
    if (e.which == 13) {
        $(this).parent().find('input[type=submit]').trigger('click');
        return false;
     }
});

This works on the assumes that the textbox and submit button are wrapped on the same div. works a treat with multiple search boxes on a page

这适用于假设文本框和提交按钮包装在同一个 div 上的情况。对页面上的多个搜索框进行处理

回答by Gibolt

Use event.keyinstead of event.keyCode!

使用event.key代替event.keyCode

function onEvent(event) {
    if (event.key === "Enter") {
        // Submit form
    }
};

Mozilla Docs

Mozilla 文档

Supported Browsers

支持的浏览器

回答by Abdelhamed Mohamed

 // jquery press check by Abdelhamed Mohamed


    $(document).ready(function(){
    $("textarea").keydown(function(event){
        if (event.keyCode == 13) {
         // do something here
         alert("You Pres Enter");
        }
       });
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <textarea></textarea>

回答by ???? ?????

You need to create a handler for the onkeypressaction.

您需要为该onkeypress操作创建一个处理程序。

HTML

HTML

<input name="keywords" type="text" id="keywords" size="50" onkeypress="handleEnter(this, event)" />

JS

JS

function handleEnter(inField, e)
{
    var charCode;

    //Get key code (support for all browsers)
    if(e && e.which)
    {
        charCode = e.which;
    }
    else if(window.event)
    {
        e = window.event;
        charCode = e.keyCode;
    }

    if(charCode == 13)
    {
       //Call your submit function
    }
}

回答by scoota269

Use an onsubmit attribute on the form tag rather than onclick on the submit.

在表单标签上使用 onsubmit 属性而不是 onclick 提交。

回答by ch.smrutiranjan parida

<form action="#">
    <input type="text" id="txtBox" name="txt" onkeypress="handle" />
</form>






<script>
    $("#txtBox").keypress(function (e) {
            if (e.keyCode === 13) {
                alert("Enter was pressed was presses");
            }

            return false;
        });

    </script>