How to Detect Enter Key Press in Javascript
In this tutorial, you will learn how to detect enter key press in javascript. Certain keyboard events get fired whenever a user interacts with your website by pressing keyboard keys. There are 3 keyboard events keyup, keydown
, and keypress
.
Generally, whenever we want to send certain data to the server, we make use of a form element with a submit button. As soon as submit button is clicked, the form data is sent to the server. In such a situation, you can also use Enter key to trigger the submission process.
Whenever a keyboard event is fired, the event object contains a keycode
property. In javascript, each key has an associated keycode
. This keycode
can help us in detecting which key is pressed by the user. To accomplish our goal, we will use the keyup
event; however, you can go with any keyboard event of your choice.
In the following example, we have one input field. We will enter some random text and press the Enter key. After the Enter key is pressed, we will log the text present in the input field in the console window. Please have a look over the code example and the steps given below.
HTML & CSS
- We have 2 elements in the HTML file (
div
andinput
). - The
div
element is just a wrapper for theinput
element. We are using thestyle
attribute here just to center align theinput
element horizontally. - We have also included our javascript file
script.js
with ascript
tag at the bottom.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <div style="text-align: center"> <input type="text" placeholder="Enter Text"> </div> <script src="script.js"></script> </body> </html>
Javascript
- We have selected the
input
element using thedocument.querySelector()
method and stored it in theinput
variable. - We have attached a
keyup
event listener to theinput
element. - In the event handler function, we are making use of the
if
statement to detect which key is pressed by the user. - The
keycode
for Enter key is 13, so if the value of thekeycode
property is equivalent to 13, that means the user has pressed Enter key and we will simply log the value present in the input field in the console window.
let input = document.querySelector('input'); input.addEventListener('keyup', (e) => { if(e.keyCode === 13) { console.log(e.target.value); } })