jQuery keypress()

Introduction

Count the number of key presses in an <input> field:

View in separate window

<!DOCTYPE html>
<html>
<head>
<script 
 src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
</script>/*from w  w w. j  a  v  a2  s  .  c o m*/
<script>
i = 0;
$(document).ready(function(){
  $("input").keypress(function(){
    $("span").text(i += 1);
  });
});
</script>
</head>
<body>

Enter your name: <input type="text">

<p>Keypresses: <span>0</span></p>

</body>
</html>

The keypress() method triggers the keypress event.

The keypress() method runs a function when a keypress event occurs.

The key press event is not fired for ALT, CTRL, SHIFT, ESC.

Use the keydown() method to check these keys.

Trigger the keypress event for the selected elements:

$(selector).keypress()

Attach a function to the keypress event:

$(selector).keypress(function)
Parameter Optional Description
function Optional.function to run when the keypress event is triggered



PreviousNext

Related