Detect the Enter key in a text input field

05/08/2020 17:00:01

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 ($(".input1").is(":focus") && (e.keyCode == 13)) {
        // Do something
    }
});

Is there a better way of doing this which would say, if enter pressed on .input1 do function?

Verified Answer (491 Votes)

08/15/2011 05:41:49
$(".input1").on('keyup', function (e) {
    if (e.keyCode === 13) {
        // Do something
    }
});


//keyup not compatible with Jquery select(), Keydown is.
491

Answer #2 (117 Votes)

09/06/2017 02:15:01

event.key === "Enter"

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

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

If you must use jQuery:

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

Mozilla Docs

Supported Browsers

117

Answer #3 (44 Votes)

08/15/2011 05:44:49
$(document).keyup(function (e) {
    if ($(".input1:focus") && (e.keyCode === 13)) {
       alert('ya!')
    }
 });

Or just bind to the input itself

$('.input1').keyup(function (e) {
    if (e.keyCode === 13) {
       alert('ya!')
    }
  });

To figure out which keyCode you need, use the website http://keycode.info

44
3
Hack Hex uses Stack Exchance API by the Stack Exchange Inc. to scrape questions/answers under Creative Commons license.