Skip to main content

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

Submitted by admin on Thu, 12/16/2021 - 18:44
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.


<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.


<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


<!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>

Category

Add new comment

Restricted HTML

  • Allowed HTML tags: <a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.