We can use the jQuery keydown method to run a function when a user types something into an input field. To do this we can add a function call to the keydown() method.

$("input").keydown(function() {
  //This user has typed in the input field

Another way this can be done is to use the .on() method:

$('input').on("keydown", function() {
    //This user has typed in the input field

The jQuery keydown() method is very similar to the keyup() method, the main difference being that the keydown method will fire once a key is pressed, while the keyup method will only run once the key is pressed AND released.

An example using the jQuery keydown method

In this example, we will just have a simple input field with a div below it. When a user enters a key in the input field, we will display what key was pressed below. Here is the HTML setup:

Type any key below

We will use the jQuery keydown() method to run the function below. The function will retrieve the key that was pressed and display that below in the results div using the jQuery text() method.

Here is the JavaScript code:


The final code and output for this example of using the keydown() method is below:

Code Output:

Type any key below

Full Code:

Type any key below

<script> $('#textInput').keydown(function(e){ $('#result').text(e.code); }); </script>

Hopefully this article has been useful to help you understand how to use the jQuery keydown() method.

Categorized in:


Last Update: February 26, 2024