Detect the Enter key in a text input field

后端 未结 10 712
粉色の甜心
粉色の甜心 2020-11-29 16:20

I\'m trying to do a function if enter is pressed while on specific input.

What I\'m I doing wrong?

$(document).keyup(function (e) {
    if ($(\".inpu         


        
10条回答
  •  [愿得一人]
    2020-11-29 17:03

    event.key === "Enter"

    More recent and much cleaner: use event.key. No more arbitrary number codes!

    NOTE: The old properties (.keyCode and .which) are Deprecated.

    const node = document.getElementsByClassName("input")[0];
    node.addEventListener("keyup", function(event) {
        if (event.key === "Enter") {
            // Do work
        }
    });
    

    Modern style, with lambda and destructuring

    node.addEventListener('keyup', ({key}) => {
        if (key === "Enter") return false
    })
    

    If you must use jQuery:

    $(document).keyup(function(event) {
        if ($(".input1").is(":focus") && event.key == "Enter") {
            // Do work
        }
    });
    

    Mozilla Docs

    Supported Browsers

提交回复
热议问题