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.
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 and input).
The div element is just a wrapper for the input element. We are using the style attribute here just to center align the input element horizontally.
We have selected the input element using the document.querySelector() method and stored it in the input variable.
We have attached a keyup event listener to the input 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 the keycode 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.