javascript

How to trigger enter key in JavaScript


In this article, you are going to learn about how to trigger an enter key in JavaScript.

Basically, we submit a form input by clicking on the button. But sometimes you need to implement the functionality where form input will be submitted by pressing an enter key from the keyboard. It is easy to implement in JavaScript. See the following example to implement this functionality.

HTML Code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Trigger enter key in Javascript</title>
</head>
<body>
    <h3>Press Enter for Trigger the Button</h3>
    <p>Press the "Enter" key to trigger the button.</p>

    <input id="myInput" value="Greetings..">
    <button id="myBtn" onclick="alert('Wecome! You Successfully triggered Enter key')">Button</button>
</body>
</html>

Here we simply take an input field and a button. We also give simple instructions for the user. But The functionality will not work as we didn’t implement our functionality yet. Let’s follow the below code to make things workable.

JavaScript Code:

<script>
    var input = document.getElementById("myInput");
    input.addEventListener("keyup", function(event) {
        if (event.keyCode === 13) {
            event.preventDefault();
            document.getElementById("myBtn").click();
            }
    });
</script>

Here we write the logic for triggering the enter button. It will also work when anyone clicks on the button. We wrote our JavaScript code into the HTML file to keep things simple you may do it in a separate file.

Note: 13 is the number of the Enter key on the keyboard.

Output: Now Its time to test our code if it is working perfectly or not.

You can see that the moment we press enter button from our keyboard an alert message has shown up immediately. The message we set in our HTML code. This is all about triggering an enter key by using JavaScript.


Share on social media

//