65.9K
CodeProject is changing. Read more.
Home

Javascript based Word Counter for text entered in a Text area, works for poastback also.

starIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIconemptyStarIcon

1.33/5 (2 votes)

Sep 8, 2006

1 min read

viewsIcon

29521

downloadIcon

127

Gives an idea about counting words entred in a text area, this will works fine whenever postback occurs also, implemented in javascript and codebehind(small portion).

Introduction

This article gives an idea about how to implement count of the words entered in a text area and stores the value of the count in an hidden variable and used whenever postbak occurs.

The javasript method wordcounter() will be called from textarea's onkeypress and onkeydown events. For postback events this method will be called from body's onload event.

The lines of javascript code written are given below.

function wordCounter(chkBodyLoad)

{

 if(chkBodyLoad == 0)

    {

        var wordcounter=0;

        var textField = event.srcElement;

// Counts the spaces and new line characters while ignoring double spaces, usually one in between each word.

        for (x=0; x < textField.value.length; x++)

        {

        if ((textField.value.charAt(x) == " " && textField.value.charAt(x-1) != " ")||textField.value.charAt(x) == "\n" && textField.value.charAt(x-1) != "\n"))

                {

                        wordcounter = wordcounter + 1;

                }

        }

        document.forms[0].hidWordCount.value = wordcounter;

        spnWordCount.innerText = wordcounter;

    }

    else if(chkBodyLoad == 1) 
    {

        spnWordCount.innerText = document.forms[0].hidWordCount.value ;

    }

}

"hidWordCount" is used for storing the word count whenever the page is submitted.

<form id=frmWordCounter runat="server">

And the method calls are given below,

onKeyDown="wordCounter(0);"

onkeyup="wordCounter(0);"
method call from body is onload="wordCounter(1);"

</form>