Navigation:    Home arrow Count Words Left
Count Words Left PDF  
Digg Reddit Ma.gnolia Stumble Upon Facebook Twitter Google Yahoo! MyWeb Furl" BlinkList Technorati Mixx Bookmark

 Sometimes you need to limit the number of input words on public forms, and it is hard for the visitor to approximate the number of words that he/she wrote already to see how much can still write. And it is annoying when after submitting the form they see the input is not valid because they wrote too many words. For this case javascript can be the best solution.

How to do this: add a small readonly input that will show the number of left words. Every time an event that means that characters are added to the textarea, a javascript function will be called. The javascript function will count the number of words that are already in the box and display the number of words left in the small input field. The function will be presented later.

The events that need to be watched are: key up, key down and paste, so we will use the functions: onKeyDown, onKeyUp and onPaste.

Here follows the html part with the form and here the function CountWordsLeft is called in the conditions discussed earlier.

 <form name="count_form" method="post" action="">

<textarea name="desc" cols="40" rows="7" id="desc"
    onKeyDown="CountWordsLeft(count_form, document.count_form.desc, document.count_form.count,100);"
    onKeyUp="CountWordsLeft(count_form, document.count_form.desc, document.count_form.count,100);"
    onPaste="CountWordsLeft(count_form, document.count_form.desc, document.count_form.count,100);">
</textarea>

<input readonly name="count" type="text" size="5" value="100">

</form>

 
The javascript function takes as parameters:
    - myForm - the name of the form
    - field - the name of the field we count words for, in out case the textarea named desc
   -
count - the name of the small readonly field that shows the left words
    - no_words - maximum number of words allowed

The function works like this: first it removes all characters in front that are not alphanumeric (it will remove spaces for example) . Then in with the resulted string all non alphanumeric characters are replaced with space (" "). Only after that the text is split using space as a separator and the resulted words are counted. The count input box is updated with the number of words left.


function CountWordsLeft(myForm, field, count, no_words) {
    var text=field.value + " ";
    if(no_words>0)
    {
        var iwhitespace = /^[^A-Za-z0-9]+/gi; // remove initial whitespace
        var left_trimmedStr = text.replace(iwhitespace, "");
        var na = rExp = /[^A-Za-z0-9]+/gi; // non alphanumeric characters
        var cleanedStr = left_trimmedStr.replace(na, " ");
        var splitString = cleanedStr.split(" ");
        var word_count = splitString.length -1;
        count.value=no_words-word_count;
    }
}