How to detect pressing Enter on keyboard using jQuery?

932,674

Solution 1

The whole point of jQuery is that you don't have to worry about browser differences. I am pretty sure you can safely go with enter being 13 in all browsers. So with that in mind, you can do this:

$(document).on('keypress',function(e) {
    if(e.which == 13) {
        alert('You pressed enter!');
    }
});

Solution 2

I wrote a small plugin to make it easier to bind the "on enter key pressed" event:

$.fn.enterKey = function (fnc) {
    return this.each(function () {
        $(this).keypress(function (ev) {
            var keycode = (ev.keyCode ? ev.keyCode : ev.which);
            if (keycode == '13') {
                fnc.call(this, ev);
            }
        })
    })
}

Usage:

$("#input").enterKey(function () {
    alert('Enter!');
})

Solution 3

I couldn't get the code posted by Paolo Bergantino to work, but when I changed it to $(document) and e.which instead of e.keyCode then I found it to work faultlessly.

$(document).keypress(function(e) {
    if(e.which == 13) {
        alert('You pressed Enter!');
    }
});

Link to example on JS Bin

Solution 4

I found this to be more cross-browser compatible:

$(document).keypress(function(event) {
    var keycode = event.keyCode || event.which;
    if(keycode == '13') {
        alert('You pressed a "enter" key in somewhere');    
    }
});

Solution 5

You can do this using the jQuery 'keydown' event handler:

$("#start").on("keydown", function(event) {
  if(event.which == 13)
    alert("Entered!");
});
Share:
932,674
chris
Author by

chris

Updated on July 08, 2022

Comments

  • chris
    chris almost 2 years

    I would like to detect whether the user has pressed Enter using jQuery.

    How is this possible? Does it require a plugin?

    EDIT: It looks like I need to use the keypress() method.

    I wanted to know if anyone knows if there are browser issues with that command - like are there any browser compatibility issues I should know about?

  • Incognito
    Incognito about 13 years
    I'm linking to this because I read this and left scratching my head over why keypress didn't work with IE. (it won't bind to $(window) under IE) quirksmode.org/dom/events/keys.html
  • Daniel
    Daniel over 12 years
    e.keyCode is not 100% cross browser. use e.which instead as shown below
  • Umesh Rajbhandari
    Umesh Rajbhandari over 12 years
    For me e.which does not work with IE. Does it work for others?
  • Ian Roke
    Ian Roke about 12 years
    Which version of IE? Works fine for me on IE7.
  • Riccardo Galli
    Riccardo Galli almost 12 years
    From the jQuery documentation "The event.which property normalizes event.keyCode and event.charCode. It is recommended to watch event.which for keyboard key input."
  • Riccardo Galli
    Riccardo Galli almost 12 years
    From the jQuery documentation "The event.which property normalizes event.keyCode and event.charCode. It is recommended to watch event.which for keyboard key input."
  • user956584
    user956584 about 11 years
    $(document).on('keypress', function(e) {
  • dpb
    dpb almost 11 years
    I'm getting multiple executions of the given function due to event propagation (ie, the alert is being thrown twice). To stop this, add an e.stopPropagation() at the end of the function
  • Rápli András
    Rápli András over 10 years
    This doesn't work for me (i got #input on the <input> field)
  • bobbdelsol
    bobbdelsol over 9 years
    The Jquery documentations says Note: as the keypress event isn't covered by any official specification, the actual behavior encountered when using it may differ across browsers, browser versions, and platforms. so unless you have an issue with keydown, why not use the one that is official
  • bumbumpaw
    bumbumpaw over 9 years
    I'm also getting multiple executions of the given function (ie, the alert is being thrown twice). I already add an e.stopPropagation() at the end of the function but nothing happens
  • Rob Erskine
    Rob Erskine about 9 years
    $(document).keypress(function(e) {if(e.which === 13) { $("form").submit(); } });
  • Ash
    Ash almost 8 years
    A list and an interactive key code generator is available at javascriptkeycode.com. Useful if you want a key code and don't already know the numeric value it corresponds to.
  • pistol-pete
    pistol-pete almost 8 years
    Your Ternary IF can be shortened to: var keycode = event.keyCode || event.which;
  • ScottyG
    ScottyG over 7 years
    As seen in one of the answers below, I needed to use the 'keydown' event, keypress did not work in Chrome for me.
  • Jigar7521
    Jigar7521 over 7 years
    What about if #input element will be dynamic?
  • SaschaM78
    SaschaM78 over 5 years
    Could you add a bit of explanatory comments to explain the asker how your code works - thanks.
  • Nico Haase
    Nico Haase about 5 years
    This looks like an adaption of other answers - could you add some explanation to make yours as interesting as the others?
  • Andrea
    Andrea over 4 years
    @mplungjan not sure what you mean by "delegating"
  • mplungjan
    mplungjan over 4 years
    $("#input").on("someevent","someselector",function () {})
  • YellowAfterlife
    YellowAfterlife over 4 years
    To note, the reason to why keypress isn't in spec (anymore) is that it's been deprecated (MDN).
  • Hannes Schneidermayer
    Hannes Schneidermayer over 4 years
    Always use === to prevent unexpected type coercion.
  • Faisal
    Faisal almost 4 years
    I use this answer because of I need to check from specific input id. Thanks
  • Dan
    Dan almost 4 years
    should be 'keydown'
  • Jorge Mauricio
    Jorge Mauricio over 3 years
    For buttons inside forms, I put this line before the alert (or the action): event.preventDefault(); It prevents the form submission.
  • Oliver M Grech
    Oliver M Grech almost 3 years
    Since it's a keydown, I am paranoid this will multi-trigger if the user holds the enter keypressed. Usually I prefer keyup. For some use cases this might be required though. Just my opinion.
  • Peter Mortensen
    Peter Mortensen about 2 years
    You ought to spend some time explaining your solution. An explanation would be in order. E.g., what is the idea/gist? From the Help Center: "...always explain why the solution you're presenting is appropriate and how it works". Please respond by editing (changing) your answer, not here in comments (without "Edit:", "Update:", or similar - the answer should appear as if it was written today).
  • Peter Mortensen
    Peter Mortensen about 2 years
    But an explanation would be in order. How does it work? By some DOM magic? What is the idea/gist? From the Help Center: "...always explain why the solution you're presenting is appropriate and how it works". Please respond by editing (changing) your answer, not here in comments (without "Edit:", "Update:", or similar - the answer should appear as if it was written today). work?
  • Peter Mortensen
    Peter Mortensen about 2 years
    But the question said "I would like to detect whether the user has pressed Enter using jQuery." Why is this an appropriate solution anyway?