Home / Count the words in a textarea or input with jQuery

Count the words in a textarea or input with jQuery

This post shows how to get a word count from an HTML textarea or text input using jQuery and display it on the page. The word count is updated as the user types.

Example

Here’s a couple of examples. These won’t work if you are reading this in a feed reader so you’ll need to click through to read this post in a web browser.


The HTML

Here’s the HTML form:

<form>

<div id="example1_count" style="display:none"></div>
<textarea id="example1" rows="5" cols="50" class="word_count">a b c</textarea>

<div id="example2_count" style="display:none"></div>
<input id="example2" type="text" size="50" class="word_count" />

</form>

Note that the textarea and input have the class "word_count" and need to have id="…". The area that contains the word count is the same id plus "_count". The divs containing the count are initially hidden (this would be better defined in a style sheet) and are made visible by the initialization code.

The jQuery / Javascript

When the document is ready all inputs with class word_count have an initial word count done to them and the word_count() function is bound to the keyup event. I tried this with the change event but that only fires when the user clicks/tabs out of the field.

$(document).ready(function() {

    $('.word_count').each(function() {
        var input = '#' + this.id;
        var count = input + '_count';
        $(count).show();
        word_count(input, count);
        $(this).keyup(function() { word_count(input, count) });
    });

});

function word_count(field, count) {

    var number = 0;
    var matches = $(field).val().match(/b/g);
    if(matches) {
        number = matches.length/2;
    }
    $(count).text( number + ' word' + (number != 1 ? 's' : '') + ' approx');

}

The word counts seem to be quite accurate using the b word boundary, although in all browsers I tested .length returns twice the actual number, hence the division by 2.

The result from .match() are returned into a variable instead of just getting .length to prevent Javascripts errors being triggered in the browser if there are no matches.

The only issue I have found is if the user uses their mouse to copy and paste, select and delete, etc then the word count isn’t updated. I couldn’t find a satisfactory way to fix this.

Browsers tested

I have tested the above code in IE6, IE7, IE8, FF1, FF3.5, Chrome 2. It worked in all of them. I tested with 9000 words generated from lipsum.com and it all worked nicely.