Detect the Enter key in a text input field

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?


$(".input1").on('keyup', function (e) {
    if (e.key === 'Enter' || e.keyCode === 13) {
        // Do something

// e.key is the modern way of detecting keys
// e.keyCode is deprecated (left here for for legacy browsers support)
// keyup is not compatible with Jquery select(), Keydown is.

Leave a Reply

Your email address will not be published. Required fields are marked *