This post will discuss how to detect whether the user has pressed Enter in JavaScript and jQuery.

The idea is to bind an event handler to the keydown or keyup JavaScript event and use that handler to check for the Enter key. There are several properties in the KeyboardEvent object, which returns the value of the key pressed by the user.

1. Using jQuery

To watch for the keyboard key input, you can use the event.which property in jQuery. The following example binds an event handler to the keyup event using the .keyup(handler) method and then matches the keyCode value against number 13 to check if the Enter key is pressed.

JS


HTML



Edit in JSFiddle

2. Using JavaScript

In plain JavaScript, you can use the EventTarget.addEventListener() method to listen for keyup event. When it occurs, check the keyCode‘s value to see if an Enter key is pressed.

JS


HTML



Edit in JSFiddle

 
Note that KeyboardEvent.keyCode attribute is deprecated, you should use the KeyboardEvent.code instead. It is set to the string Enter whenever the Enter key is pressed.

JS


HTML



Edit in JSFiddle

 
You can also use the KeyboardEvent.key attribute similarly.

JS


HTML



Edit in JSFiddle

That’s all about detecting whether a user has pressed Enter in JavaScript and jQuery.