How to use keydown() event In Javascript

This event occurs when a keyboard key is pressed. The method either triggers the keydown event, or to run a function when a keydown event occurs. 

Syntax:

It triggers the keydown event for the selected element. It Attaches a function to the keydown event.

$(selector).keydown(function);

Example : This example uses keydown() event to trigger enter key as a button.

HTML




<!DOCTYPE html>
<html>
<head>
    <title>
        Rename object key in JavaScript
    </title>
    <script src=
"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
    </script>
</head>
 
<body>
    <h1 style="color:green;">
        w3wiki
    </h1>
 
    Username:<input id="uname" type="text">
    <br>
    Password:<input id="pass" type="password">
    <br>
    <button id="GFG_Button">Submit</button>
    <p id="gfg"></p>
    <script>
        $("#pass").keydown(function (event) {
            if (event.keyCode === 13) {
                $("#GFG_Button").click();
            }
        });
 
        $("#GFG_Button").click(function () {
            document.getElementById("gfg").innerHTML
           = "Button clicked"
        });
    </script>
</body>
</html>


Output:

JavaScript Trigger a button on ENTER key

JavaScript Trigger a button on ENTER key

In this article, we will see how to trigger a button on the ENTER key. To trigger a click button on ENTER key, We can use any of the keyup(), keydown() and keypress() events of jQuery.

Table of Content

  • Using keyup() event
  • Using keydown() event
  • Using keypress() event

Similar Reads

Method 1: Using keyup() event:

This event occurs when a keyboard key is released. The method either triggers the keyup event or runs a function when a keyup event occurs....

Method 2: Using keydown() event:

...

Method 3: Using keypress() event:

This event occurs when a keyboard key is pressed. The method either triggers the keydown event, or to run a function when a keydown event occurs....

Contact Us