385

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?

jQuerybeast
  • 13,589
  • 36
  • 117
  • 190
  • 2
    Possible duplicate of [Enter key press event in JavaScript](http://stackoverflow.com/questions/905222/enter-key-press-event-in-javascript) – Bae Mar 23 '16 at 21:17
  • All the solutions are valid, but keep in mind you should use e.key or e.code, as e.which and e.keyCode are both deprecated. You can find the right values for the keys you want to detect here: https://keyjs.dev – Danziger Sep 27 '20 at 04:45

11 Answers11

626
$(".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.
Paweł Gościcki
  • 8,327
  • 5
  • 65
  • 76
Joseph Silber
  • 205,539
  • 55
  • 352
  • 286
  • 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). – Joseph Silber Aug 15 '11 at 00:47
  • Isn't `65` they keyCode for `a`? [jsFiddle](http://jsfiddle.net/alexdickson/kc3As/). – alex Aug 15 '11 at 00:47
  • 2
    Your code wasnt working because you used .is() and needed === rather than ==. See my answer for some more details. – wesbos Aug 15 '11 at 00:48
  • @alex: Correct. I just copied his keyCode without thinking. Updated! – Joseph Silber Aug 15 '11 at 00:49
  • @alex if you use input is focus and keycode then you use triple ===. Just learned that – jQuerybeast Aug 15 '11 at 00:56
  • 7
    @jQuerybeast It's not *needed*, and `event.keyCode` is a `Number`, so JavaScript will take the same steps with `==` or `===`. – alex Aug 15 '11 at 01:47
  • BTW If the form happens to submit because youve pressed enter, the keyup event doesnt get fired - the input looses focus. in my firefox. – commonpike Apr 02 '13 at 22:19
  • 7
    e.which is declared to be more useful cross browsers – mohammad eslahi sani Nov 10 '15 at 17:55
  • I'd recommend to use `$('.input1').on('keyup', function (e) {});` instead for better compatibility. – Daniel Dewhurst Oct 10 '16 at 12:56
  • 3
    Properties `which`, `code`, `charCode` and `keyCode` is deprecated https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent, please add actual information to your answer. – Sasay Oct 03 '19 at 17:34
200

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

Gibolt
  • 33,561
  • 12
  • 157
  • 107
45
$(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

wesbos
  • 25,091
  • 29
  • 101
  • 142
  • 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 – jQuerybeast Aug 15 '11 at 00:54
  • np, you should always be using === – wesbos Aug 15 '11 at 00:55
13

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

$(function(){

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

});
ShankarSangoli
  • 68,720
  • 11
  • 89
  • 123
8

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;
    }
});
Roy Shoa
  • 2,967
  • 1
  • 34
  • 40
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>
Indra Kumar S
  • 2,660
  • 2
  • 14
  • 25
4

The solution that work for me is the following

$("#element").addEventListener("keyup", function(event) {
    if (event.key === "Enter") {
        // do something
    }
});
Jorge Santos Neill
  • 1,375
  • 9
  • 6
1

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

jonathan klevin
  • 165
  • 1
  • 2
0
 $(document).ready(function () {
        $(".input1").keyup(function (e) {
            if (e.keyCode == 13) {
                // Do something
            }
        });
    });
Jobelle
  • 2,570
  • 1
  • 14
  • 21
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;
 }
});
Umar Niazi
  • 376
  • 3
  • 14
-1

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);
    }
}
Omzig
  • 756
  • 1
  • 11
  • 18