在文本框中按 Enter 时如何触发 HTML 按钮?

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

How to trigger HTML button when you press Enter in textbox?

htmlbuttoninputtextbox

提问by Ben

So the code that I have so far is:

所以到目前为止我的代码是:

<fieldset id="LinkList">
    <input type="text" id="addLinks" name="addLinks" value="http://">
    <input type="button" id="linkadd" name="linkadd" value="add">
</fieldset>

It is not in a <form>and is just as it is within a <div>. However when I type something into the textboxcalled "addLinks" I want the user to be able to press Enter and trigger the "linkadd" buttonwhich will then run a JavaScript function.
How can I do this?
Thanks

它不在 a 中<form>,就像在 a 中一样<div>。但是,当我在textbox名为“addLinks”的内容中键入内容时,我希望用户能够按 Enter 并触发“linkadd” button,然后该“linkadd”将运行 JavaScript 函数。
我怎样才能做到这一点?
谢谢

Edit:I did find this code, but it doesnt seem to work.

编辑:我确实找到了这段代码,但它似乎不起作用。

$("#addLinks").keyup(function(event){
    if(event.keyCode == 13){
        $("#linkadd").click();
    }
});

回答by Man Programmer

$(document).ready(function(){
    $('#TextBoxId').keypress(function(e){
      if(e.keyCode==13)
      $('#linkadd').click();
    });
});

回答by Константин Ван

It is…… 2020. And I believe this still holds true.

现在是…… 2020 年。我相信这仍然适用。



DO NOT USE keypress

不使用 keypress

  1. keypressevent is not triggeredwhen the user presses a key that does not produce any character, such as Tab, Caps Lock, Delete, Backspace, Escape, left & right Shift, function keys(F1- F12).

    keypressevent Mozilla Developer Network

    The keypressevent is fired when a key is pressed down, and that key normally produces a character value. Use inputinstead.

  2. It has been deprecated.

    keypressevent UI Events(W3C working draft published on November 8, 2018.)

    • NOTE| The keypressevent is traditionally associated with detecting a character valuerather than a physical key, and might not be available on all keys in some configurations.
    • WARNING| The keypressevent type is defined in this specification for reference and completeness, but this specification deprecatesthe use of this event type.When in editing contexts, authors can subscribe to the beforeinputevent instead.
  1. keypress当用户按下不产生任何字符的键不会触发事件,例如, , , , , left & right , function keys( - )。TabCaps LockDeleteBackspaceEscapeShiftF1F12

    keypress活动Mozilla 开发者网络

    keypress按下某个键时会触发该事件,该键通常会产生一个字符值。使用input来代替。

  2. 它已被弃用。

    keypress事件UI 事件(W3C 工作草案于 2018 年 11 月 8 日发布。)

    • 注意| 该keypress事件传统上与检测字符值而不是物理键相关联,并且在某些配置中可能不适用于所有键。
    • 警告| 的keypress事件类型是在本说明书中以供参考和完整性所定义,但本说明书中不赞成使用该事件类型的。在编辑上下文时,作者可以beforeinput改为订阅事件。


DO NOT USE KeyboardEvent.keyCode

不使用 KeyboardEvent.keyCode

  1. It has been deprecated.

    KeyboardEvent.keyCodeMozilla Developer Network

    Deprecated| This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility tableat the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

  1. 它已被弃用。

    KeyboardEvent.keyCodeMozilla 开发者网络

    已弃用| 不再推荐此功能。虽然一些浏览器可能仍然支持它,但它可能已经从相关的 Web 标准中删除,可能正在被删除,或者可能只是为了兼容性目的而保留。避免使用它,并尽可能更新现有代码;请参阅本页底部的兼容性表以指导您的决定。请注意,此功能可能随时停止工作。



What should I use then? (The good practice)

那我应该用什么?(好的做法)

// Make sure this code gets executed after the DOM is loaded.
document.querySelector("#addLinks").addEventListener("keyup", event => {
    if(event.key !== "Enter") return; // Use `.key` instead.
    document.querySelector("#linkadd").click(); // Things you want to do.
    event.preventDefault(); // No need to `return false;`.
});

回答by dmitry_romanov

There are a js-free solution.

有一个无js的解决方案。

Set type=submitto the button you'd like to be default and type=buttonto other buttons. Now in the form below you can hit Enter in any input fields, and the Renderbutton will work (despite the fact it is the second button in the form).

设置type=submit为您希望成为默认type=button按钮的按钮和其他按钮。现在在下面的表单中,您可以在任何输入字段中按 Enter,该Render按钮将起作用(尽管它是表单中的第二个按钮)。

Example:

例子:

    <button id='close_renderer_button' class='btn btn-success'
            title='Перейти к редактированию программы'
            type=button>
      <span class='glyphicon glyphicon-edit'> </span> Edit program
    </button>
    <button id='render_button' class='btn btn-primary'
            title='Построить фрактал'
            type=submit
            formaction='javascript:alert("Bingo!");'>
      <span class='glyphicon glyphicon-send'> </span> Render
    </button>

Tested in FF24 and Chrome 35 (formactionis html5 feature, but typeis not).

在 FF24 和 Chrome 35 中测试(formaction是 html5 功能,但type不是)。

回答by Quentin

  1. Replace the buttonwith a submit
  2. Be progressive, make sure you have a server side version
  3. Bind your JavaScript to the submithandler of the form, not the clickhandler of the button
  1. 替换buttonsubmit
  2. 渐进的,请确保您有一个服务器端版本
  3. 将您的 JavaScript 绑定到submit表单的click处理程序,而不是按钮的处理程序

Pressing enter in the field will trigger form submission, and the submit handler will fire.

在字段中按 Enter 将触发表单提交,并且提交处理程序将触发。

回答by Asad Saeeduddin

You could add an event handler to your input like so:

您可以将事件处理程序添加到您的输入中,如下所示:

document.getElementById('addLinks').onkeypress=function(e){
    if(e.keyCode==13){
        document.getElementById('linkadd').click();
    }
}

回答by Sud

It works when input type="button" is replaced with input type="submit" for the default button which needs to be triggered.

当需要触发的默认按钮的 input type="button" 替换为 input type="submit" 时,它会起作用。

回答by Pablo Werlang

Based on some previous answers, I came up with this:

根据之前的一些答案,我想出了这个:

<form>
  <button id='but' type='submit'>do not click me</button>
  <input type='text' placeholder='press enter'>
</form>

$('#but').click(function(e) {
  alert('button press');
  e.preventDefault();
});

Take a look at the Fiddle

看看小提琴

EDIT: If you dont want to add additional html elements, you can do this with JS only:

编辑:如果你不想添加额外的 html 元素,你只能用 JS 来做到这一点:

    $("input").keyup(function(event) {
        if (event.keyCode === 13) {
            $("button").click();
        }
    });     

回答by Anshu

This should do it, I am using jQuery you can write plain javascript.
Replace sendMessage()with your functionality.

这应该可以,我正在使用 jQuery,您可以编写普通的 javascript。
替换sendMessage()为您的功能。

$('#addLinks').keypress(function(e) {
    if (e.which == 13) {
        sendMessage();
        e.preventDefault();
    }
});

回答by Milind Anantwar

First of all add jquery library file jqueryand call it in your html head.

首先添加 jquery 库文件jquery并在您的 html head 中调用它。

and then Use jquery based code...

然后使用基于 jquery 的代码...

$("#id_of_textbox").keyup(function(event){
    if(event.keyCode == 13){
        $("#id_of_button").click();
    }
});

回答by Scott Tovey

I found w3schools.com howto, their try me page is at the following.

我找到了 w3schools.com howto,他们的 try me 页面在下面。

https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_trigger_button_enter

https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_trigger_button_enter

This worked in my regular browser but did not work in my php app which uses the built in php browser.

这在我的常规浏览器中有效,但在我使用内置 php 浏览器的 php 应用程序中无效。

After toying a bit I came up with the following pure JavaScript alternative that works for my situation and should work in every other situation:

在玩弄了一下之后,我想出了以下纯 JavaScript 替代方案,它适用于我的情况并且应该适用于所有其他情况:

    function checkForEnterKey(){
        if (event.keyCode === 13) {
            event.preventDefault();
            document.getElementById("myBtn").click();
        }
    }

    function buttonClickEvent()
    {
        alert('The button has been clicked!');
    }

HTML Press the enter key inside the textbox to activate the button.

HTML 在文本框中按回车键激活按钮。

    <br />
    <input id="myInput" onkeyup="checkForEnterKey(this.value)">
    <br />
    <button id="myBtn" onclick="buttonClickEvent()">Button</button>