How to detect pressing Enter on keyboard | jQuery

The jQuery keydown() is an inbuilt method in jQuery which triggers the keydown event, or attaches a function to run when a keydown event occurs.
$(selector).keydown()
Example
$('#myTxt').keydown(function (e){ if(e.keyCode == 13){ alert('you pressed enter key'); } })

The order of events related to the keydown event:

  1. keydown : The key is on its way down
  2. keypress : The key is pressed down
  3. keyup : The key is released
The keydown event is sent to an element when the user presses a key on the keyboard. If the key is kept pressed, the event is sent every time the operating system repeats the key. It can be attached to any element, but the event is only sent to the element that has the focus. The following example will display the text input field in an alert box when you press the enter key on the keyboard.

Detect ENTER key press event | jQuery

run this source code Browser View

Type something and press Enter key:

Full Source | jQuery
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script> $(document).ready(function(){ $('#myTxt').keydown(function (e){ if(e.keyCode == 13){ alert('you pressed enter key'); } }) }); </script> </head> <body> <p>Type something and press Enter key:</p> <input type="text" id="myTxt"/> </body> </html>
As the .keydown() method is just a shorthand for .on( "keydown", handler ), detaching is possible using .off( "keydown" ).

jQuery .keypress()


How can I detect pressing Enter on the keyboard using jQuery?
The keypress event is sent to an element when the browser registers keyboard input.
$('#myTxt').keypress(function (e){ if(e.keyCode == 13){ alert('you pressed enter key'); } })

jQuery .keyup()

The keyup event is sent to an element when the user releases a key on the keyboard.
$('#myTxt').keyup(function (e){ if(e.keyCode == 13){ alert('you pressed enter key'); } })

jQuery .keyup() event can be attached to any element, but the event is only sent to the element that has the focus.

e.keyCode == 13

ENTER key is represented by ASCII code "13". In order to check whether user pressed ENTER key on webpage or on any input element, you can bind keypress or keydown event to that element or document object itself.
if(e.keyCode == 13){ alert('you pressed enter key'); }
If ascii code of key pressed is 13 then ENTER key was pressed; otherwise some other key was pressed.