Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

How to count words in real time using jQuery ?

  • Last Updated : 25 May, 2021

In this article, we will learn how to count words in real-time using jQuery. We have an input field, and when we type, we get the number of words in the input in real-time.

Approach: First, we select the input field and store its value into a variable. We call a function called wordCount() when a keyboard key is released that counts the number of words in the input field. To count the number of words in the input field, we split the value by space using jQuery split() method and then count the number of words. 

Code snippet: The following is the implementation of the method wordCount().

function wordCount( field ) {
    var number = 0;
    
    // Split the value of input by
    // space to count the words
    var matches = $(field).val().split(" ");
        
    // Count number of words
    number = matches.filter(function (word) {
        return word.length > 0;
    }).length;
        
    // final number of words
    $("#final").val(number);
}

HTML code: Below is the full implementation of the above approach.

HTML




<!DOCTYPE html>
<html lang="en">
  
<head>
    <script src=
    </script>
  
    <style>
        body {
            color: green;
            font-size: 30px;
        }
  
        input {
            font-size: 30px;
            color: green;
        }
    </style>
</head>
  
<body>
    <h1>GeeksforGeeks</h1>
    <input type="text" id="inp" />
    <input type="text" id="final" disabled />
  
    <script>
        function wordCount(field) {
            var number = 0;
  
            // Split the value of input by
            // space to count the words
            var matches = $(field).val().split(" ");
  
            // Count number of words
            number = matches.filter(function (word) {
                return word.length > 0;
            }).length;
  
            // Final number of words
            $("#final").val(number);
        }
  
        $(function () {
            $("input[type='text']:not(:disabled)")
            .each(function () {
                var input = "#" + this.id;
  
                // Count words when keyboard
                // key is released
                $(this).keyup(function () {
                    wordCount(input);
                });
            });
        });
    </script>
</body>
  
</html>

Output:




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!