449

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?

0

14 Answers 14

699
$(".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.
Sign up to request clarification or add additional context in comments.

5 Comments

Which browser were you testing it in? I think older versions of IE don't trigger keyup events on the document (not sure about this though).
Your code wasnt working because you used .is() and needed === rather than ==. See my answer for some more details.
BTW If the form happens to submit because youve pressed enter, the keyup event doesnt get fired - the input looses focus. in my firefox.
I'd recommend to use $('.input1').on('keyup', function (e) {}); instead for better compatibility.
Properties which, code, charCode and keyCode is deprecated developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent, please add actual information to your answer.
256

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("input1")[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") {
        // Do work
    }
})

If you must use jQuery:

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

Mozilla Docs

Supported Browsers

4 Comments

kudos for the plain javascript version, not sure why all the others are in jquery
Because, the OP put his example code in jQuery and (as well as JavaScript) jQuery is tagged.
Dear Sirs, in the modern style one, what's the purpose of {} around key? TIA
@rlatief It's a destructuring assignment which allows assignment of object properties directly to variables. We see here this arrow function accepts one parameter, which in an Event object. But we only care about the key property of that object. Wrapping the property name with {} allows it to be scoped to the arrow function as a new variable with less code -- no need for event.key
44
$(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

2 Comments

Thank you. I've learned something new. By the way I used .is() ALOT of times so it is not logic, not to be working. Also the ==, again I used two == for other situations
np, you should always be using ===
14

Try this to detect the Enter key pressed in a textbox.

$(function(){

$(".input1").keyup(function (e) {
    if (e.which == 13) {
        // Enter key pressed
    }
 });

});

Comments

10

The best way I found is using keydown ( the keyup doesn't work well for me).

Note: I also disabled the form submit because usually when you like to do some actions when pressing Enter Key the only think you do not like is to submit the form :)

$('input').keydown( function( event ) {
    if ( event.which === 13 ) {
        // Do something
        // Disable sending the related form
        event.preventDefault();
        return false;
    }
});

2 Comments

event.keyCode is deprecated event.which is not, so this is better
Funny, keydown doesn't work for me, but keyup does (:
7

The solution that work for me is the following

$("#element").addEventListener("keyup", function(event) {
    if (event.key === "Enter") {
        // do something
    }
});

Comments

6

It may be too late to answer this question. But the following code simply prevents the enter key. Just copy and paste should work.

        <script type="text/javascript"> 
        function stopRKey(evt) { 
          var evt = (evt) ? evt : ((event) ? event : null); 
          var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null); 
          if ((evt.keyCode == 13) && (node.type=="text"))  {return false;} 
        } 

        document.onkeypress = stopRKey; 

        </script>

Comments

4

A solution that worked for me is this:

<input onkeydown="if (event.key == 'Enter'){//do logic}else{}">

Comments

2

Try this to detect the Enter key pressed in a textbox.

$(document).on("keypress", "input", function(e){
    if(e.which == 13){
        alert("Enter key pressed");
    }
});

DEMO

Comments

1

In JS add event onKeyDown

 <input
     type="search"
     onKeyDown={(event) => {
     if (event.key === "Enter") {
      handleNavigation();
      }
    }}
                    
    />

Comments

0
 $(document).ready(function () {
        $(".input1").keyup(function (e) {
            if (e.keyCode == 13) {
                // Do something
            }
        });
    });

Comments

0

This code handled every input for me in the whole site. It checks for the ENTER KEY inside an INPUT field and doesn't stop on TEXTAREA or other places.

$(document).on("keydown", "input", function(e){
 if(e.which == 13){
  event.preventDefault();
  return false;
 }
});

Comments

0

Here is what I did for my angular project:

HTML:

<input
    class="form-control"
    [(ngModel)]="searchFirstName"
    (keyup)="keyUpEnter($event)"
/>

TypeScript:

keyUpEnter(event: KeyboardEvent) {
    if (event.key == 'Enter') {
        console.log(event);
    }
}

Comments

0

If anyone need one line solution:

<input type="text" onkeyup="(event.key === 'Enter') ? alert('Entered') : undefined;" placeholder="Type Something and Press Enter">

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.