826

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

How is this possible? Does it require a plugin?

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

Are there browser issues with that command - like are there any browser compatibility issues I should know about?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
chris
  • 20,791
  • 29
  • 77
  • 90
  • 6
    One of the best things in Javascript frameworks is that they should be by default cross-browser compatible. They handle the browser compatibility checks so that the user doesn't have to. I haven't read the JQuery source code but I doubt the keypress functionality is any different in that sense. – miek Jun 11 '09 at 06:54
  • 3
    the only browser compatibility issue is that you should use e.which instead of e.keyCode to detect the ascii code. – Daniel Jan 19 '12 at 18:54
  • 1
    http://stackoverflow.com/questions/302122/jquery-event-keypress-which-key-was-pressed – Lemo Jul 11 '12 at 11:07
  • link about this [.keypress() | jQuery API Documentation](http://docs.jquery.com/Events/keypress) – Haim Evgi Jun 11 '09 at 06:43

19 Answers19

1491

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!');
    }
});
Blackbam
  • 17,496
  • 26
  • 97
  • 150
Paolo Bergantino
  • 480,997
  • 81
  • 517
  • 436
  • 9
    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) http://www.quirksmode.org/dom/events/keys.html – Incognito Mar 02 '11 at 16:49
  • 18
    e.keyCode is not 100% cross browser. use e.which instead as shown below – Daniel Jan 19 '12 at 18:52
  • 15
    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 Jun 04 '12 at 09:47
  • 21
    $(document).on('keypress', function(e) { – user956584 Apr 10 '13 at 14:02
  • 6
    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 – dpb May 23 '13 at 15:31
  • 1
    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 – bobbdelsol Sep 23 '14 at 21:52
  • 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 – bumbumpaw Nov 12 '14 at 03:19
  • $(document).keypress(function(e) {if(e.which === 13) { $("form").submit(); } }); – Rob Erskine May 01 '15 at 19:47
  • A list and an interactive key code generator is available at http://www.javascriptkeycode.com/. Useful if you want a key code and don't already know the numeric value it corresponds to. – Ash Jun 28 '16 at 06:19
  • 1
    As seen in one of the answers below, I needed to use the 'keydown' event, keypress did not work in Chrome for me. – ScottyG Nov 07 '16 at 20:45
  • 1
    Always use `===` to prevent unexpected type coercion. – Hannes Schneidermayer Jan 30 '20 at 10:15
  • should be 'keydown' – Dan Jul 23 '20 at 21:48
141

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!');
})
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Andrea
  • 1,838
  • 1
  • 13
  • 7
70

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Ian Roke
  • 1,774
  • 1
  • 19
  • 27
56

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');    
    }
});
pistol-pete
  • 1,213
  • 17
  • 13
jesal
  • 7,852
  • 6
  • 50
  • 56
43

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

$("#start").on("keydown", function(event) {
  if(event.which == 13)
    alert("Entered!");
});
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Nasruddin
  • 1,640
  • 14
  • 20
  • I use this answer because of I need to check from specific input id. Thanks – Faisal Jul 13 '20 at 08:14
  • 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. – Oliver M Grech Jun 25 '21 at 06:53
24

Use event.key and modern JavaScript!

$(document).keypress(function(event) {
    if (event.key === "Enter") {
        // Do something
    }
});

Or without jQuery:

document.addEventListener("keypress", function onEvent(event) {
    if (event.key === "Enter") {
        // Do something better
    }
});

Mozilla documentation

Supported Browsers

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Gibolt
  • 42,564
  • 15
  • 187
  • 127
9

I came up with this solution:

$(document).ready(function(){

  $('#loginforms').keypress(function(e) {
    if (e.which == 13) {
    //e.preventDefault();
    alert('login pressed');
    }
  });

 $('#signupforms').keypress(function(e) {
    if (e.which == 13) {
      //e.preventDefault();
      alert('register');
    }
  });
});
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
  • 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](https://stackoverflow.com/help/promotion): *"...always explain why the solution you're presenting is appropriate and how it works"*. Please respond by [editing (changing) your answer](https://stackoverflow.com/posts/27771911/edit), not here in comments (***without*** "Edit:", "Update:", or similar - the answer should appear as if it was written today). – Peter Mortensen Apr 28 '22 at 21:02
7

A minor extension of Andrea's answer makes the helper method more useful when you may also want to capture modified enter presses (i.e., Ctrl + Enter or Shift + Enter). For example, this variant allows binding like:

$('textarea').enterKey(function() {$(this).closest('form').submit(); }, 'ctrl')

to submit a form when the user presses Ctrl + Enter with focus on that form's textarea.

$.fn.enterKey = function (fnc, mod) {
    return this.each(function () {
        $(this).keypress(function (ev) {
            var keycode = (ev.keyCode ? ev.keyCode : ev.which);
            if ((keycode == '13' || keycode == '10') && (!mod || ev[mod + 'Key'])) {
                fnc.call(this, ev);
            }
        })
    })
}

(See also *Ctrl + Enter using jQuery in a TEXTAREA)

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
joeln
  • 3,563
  • 25
  • 31
7

There's a keypress() event method. The Enter key's ASCII number is 13 and is not dependent on which browser is being used.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Richard Simões
  • 12,401
  • 6
  • 41
  • 50
4

In some cases, you may need to suppress the ENTER key for a certain area of a page but not for other areas of a page, like the page below that contains a header <div> with a SEARCH field.

It took me a bit to figure out how to do this, and I am posting this simple yet complete example up here for the community.

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>Test Script</title>
  <script src="/lib/js/jquery-1.7.1.min.js" type="text/javascript"></script>
  <script type="text/javascript">
    $('.container .content input').keypress(function (event) {
      if (event.keyCode == 10 || event.keyCode == 13) {
        alert('Form Submission needs to occur using the Submit button.');
        event.preventDefault();
      }
    });
  </script>
</head>
  <body>
    <div class="container">
      <div class="header">
        <div class="FileSearch">
          <!-- Other HTML here -->
        </div>
      </div>
      <div class="content">
        <form id="testInput" action="#" method="post">
        <input type="text" name="text1" />
        <input type="text" name="text2" />
        <input type="text" name="text3" />
        <input type="submit" name="Submit" value="Submit" />
        </form>
      </div>
    </div>
  </body>
</html>

Link to JSFiddle Playground: The [Submit] button does not do anything, but pressing ENTER from one of the Text Box controls will not submit the form.

  • But an explanation would be in order. How does it work? By some DOM magic? What is the idea/gist? From [the Help Center](https://stackoverflow.com/help/promotion): *"...always explain why the solution you're presenting is appropriate and how it works"*. Please respond by [editing (changing) your answer](https://stackoverflow.com/posts/20339685/edit), not here in comments (***without*** "Edit:", "Update:", or similar - the answer should appear as if it was written today). work? – Peter Mortensen May 04 '22 at 22:27
4

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.

$(document).keydown(function(event) {
  if (event.keyCode || event.which === 13) {
    // Cancel the default action, if needed
    event.preventDefault();
    // Call function, trigger events and everything you want to do. Example: Trigger the button element with a click
    $("#btn").trigger('click');
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<button id="btn" onclick="console.log('Button Pressed.')">&nbsp</button>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Zeinab_Ns
  • 265
  • 4
  • 10
  • 1
    To note, the reason to why `keypress` isn't in spec (anymore) is that it's been deprecated ([MDN](https://developer.mozilla.org/en-US/docs/Web/API/Document/keypress_event)). – YellowAfterlife Dec 14 '19 at 11:09
3

Try this to detect the Enter key pressed.

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

See demo @ detect enter key press on keyboard

jonathan klevin
  • 193
  • 1
  • 2
2

I used $(document).on("keydown").

On some browsers keyCode is not supported. The same with which so if keyCode is not supported you need to use which and vice versa.

$(document).on("keydown", function(e) {
  const ENTER_KEY_CODE = 13;
  const ENTER_KEY = "Enter";
  var code = e.keyCode || e.which
  var key = e.key
  if (code == ENTER_KEY_CODE || key == ENTER_KEY) {
    console.log("Enter key pressed")
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
Justin Liu
  • 581
  • 6
  • 21
1
$(document).keydown(function (event) {
      //proper indentiation of keycode and which to be equal to 13.
    if ( (event.keyCode || event.which) === 13) {
        // Cancel the default action, if needed
        event.preventDefault();
        //call function, trigger events and everything tou want to dd . ex : Trigger the button element with a click
        $("#btnsearch").trigger('click');
    }
});
0

The easy way to detect whether the user has pressed Enter is to use the key number. The Enter key number is equal to 13.

To check the value of key in your device:

$("input").keypress(function (e) {
  if (e.which == 32 || (65 <= e.which && e.which <= 65 + 25)
                    || (97 <= e.which && e.which <= 97 + 25)) {
    var c = String.fromCharCode(e.which);
    $("p").append($("<span/>"))
          .children(":last")
          .append(document.createTextNode(c));
  } else if (e.which == 8) {
    // Backspace in Internet Explorer only is on keydown
    $("p").children(":last").remove();
  }
  $("div").text(e.which);
});

By pressing the Enter key, you will get result as 13. Using the key value, you can call a function or do whatever you wish:

    $(document).keypress(function(e) {
      if(e.which == 13) {
        console.log("The user pressed the Enter key");

        // The code you want to run
      }
    });

If you want to target a button once the Enter key is pressed, you can use the code:

$(document).bind('keypress', function(e) {
  if(e.which === 13) { // Return
     $('#buttonname').trigger('click');
  }
});
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
0

I think the simplest method would be using vanilla JavaScript:

document.onkeyup = function(event) {
   if (event.key === 13){
     alert("Enter was pressed");
   }
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Duan Walker
  • 305
  • 1
  • 11
  • But the question said *"I would like to detect whether the user has pressed Enter using jQuery."* Why is this an appropriate solution anyway? – Peter Mortensen May 04 '22 at 22:30
0

This my how I solved it. You should use return false;

$(document).on('keypress', function(e) {
    if(e.which == 13) {
        $('#sub_btn').trigger('click');
        alert('You pressed the "Enter" key somewhere');
        return false;
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<form action="" method="post" id="sub_email_form">
    <div class="modal-header">
        <button type="button" class="close" id="close" data-dismiss="modal">&times;</button>
        <h4 class="modal-title">Subscribe to our Technical Analysis</h4>
    </div>
    <div class="modal-body">
        <p>Signup for our regular Technical Analysis updates to review recommendations delivered directly in your inbox.</p>
        <div class="input-group">
            <input type="email" name="sub_email" id="sub_email" class="form-control" placeholder="Enter your email" required>
        </div>
        <span id="save-error"></span>
    </div>
    <div class="modal-footer">
        <div class="input-group-append">
            <input type="submit" class="btn btn-primary sub_btn" id="sub_btn" name="sub_btn" value="Subscribe">
        </div>
    </div>
</form>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Ankit Singh
  • 327
  • 4
  • 12
-1
$(document).keyup(function(e) {
    if(e.key === 'Enter') {
        //Do the stuff
    }
});
AzizAhmad
  • 637
  • 1
  • 9
  • 20
  • 1
    This looks like an adaption of other answers - could you add some explanation to make yours as interesting as the others? – Nico Haase May 07 '19 at 06:57
-2
$(function(){
  $('.modal-content').keypress(function(e){
    debugger
     var id = this.children[2].children[0].id;
       if(e.which == 13) {
         e.preventDefault();
         $("#"+id).click();
       }
   })
});
Nisarg
  • 1,631
  • 6
  • 19
  • 31