Count The Number of keyboard Keypress in an Input Text Field Using jquery

jquery-keypress-count

In this jQuery tutorial we will display the number of keyboard keypress in an input text field.

Step 1: HTML

Create an input text filed. And regions to display keypress count.

1
2
3
<input type="text" name="" value="" />
<p class="number">Keypress Count: <span></span></p>
<p class="message">A key is pressed</p>

Step 2: jQuery

Use below jQuery code to count the keypress count in the input text field.
We can use jQuery keydown() method or keyup() method to count keypress.

1
2
3
4
5
6
7
8
9
<script type="text/javascript">
$(document).ready(function(){
  var i = 0;
  $('input[type="text"]').keyup(function(){
    $(".number span").text(i += 1);
    $('.message').show().fadeOut('slow');
  })
})
</script>

Full Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
  <meta charset="utf-8">
  <title>Count Keyboard Keypress Number</title>
  <script src="//code.jquery.com/jquery-3.4.1.min.js"></script>
  <script type="text/javascript">
    $(document).ready(function(){
      var i = 0;
      $('input[type="text"]').keyup(function(){
        $(".number span").text(i += 1);
        $('.message').show().fadeOut('slow');
      })
    })
  </script>
  <style type="text/css" media="screen">
    .message {
      display: none;
      background: #bcd6cd;
    }
  </style>
</head>
<body>
  <input type="text" name="" value="" />
  <p class="number">Keypress Count: <span></span></p>
  <p class="message">A key is pressed</p>
</body>
</html>

Demo

Count The Number of keyboard Keypress in an Input Text Field

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *