This post will discuss how to trigger a button click event on pressing the Enter key in JavaScript and jQuery.

1. Using jQuery

The idea is to bind an event handler to the keyup JavaScript event using jQuery’s .keyup(handler) method and use that handler to check for the Enter key. To determine the specific key which was pressed, you can use the event.which property. Now trigger the click event of the submit button when the Enter key is detected.

JS


HTML



Edit in JSFiddle

2. Using JavaScript

In plain JavaScript, the idea remains similar. We bind an event handler to the keyup event using the addEventListener() method and use the KeyboardEvent.keyCode property to determine whether an Enter key is pressed. Finally, trigger the button click event on Enter keypress.

JS


HTML



Edit in JSFiddle

 
Note that the keyCode attribute is no longer recommended; you should use the KeyboardEvent.code instead.

JS


HTML



Edit in JSFiddle

 
Alternatively, you can use the onkeyup property, which is fired whenever a user releases the pressed key.

JS


HTML



Edit in JSFiddle

That’s all about triggering a button click on Enter key in JavaScript and jQuery.