Counting Words

Have you ever thought that it would be useful to be able to count the number of words that have been typed into a text field or text area. Well here's a script that dynamically keeps track of how many words have been entered. Please type some text into the following text box to see how it works.

Word Count:

To implement this, all you need to do is to include the following script into the <head> section of your page:

function cnt(w,x){
var y=w.value;
var r = 0;
a=y.replace(/\s/g,' ');
a=a.split(' ');
for (z=0; z<a.length; z++) {if (a[z].length > 0) r++;}

The script changes any new line characters into single spaces and then splits the string into separate pieces wherever there is a space. All of the pieces that actually contain something are "words" and get counted. Note that because this function uses regular expressions so it will only work correctly with version 4 browsers and later.

Next we need to call this routine whenever your visitor tries to enter anything into either field (we include the count field so that anything they enter there will be changed back into the correct count of words in the field we are counting). We do this by using the onkeyup method so that the count is recalculated every time anything is typed.

<form name="myform">
<textarea rows="15" name="w" cols="45"
<br />Word Count: <input type="text" name="c" value="0" size="5"
onkeyup="cnt(document.myform.w,this)" />

In each case both fields are passed to the function in the same order (field to count words in, field to display count). You can call the fields whatever you like as long as you reference them correctly by name in the function call.


This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow