Counting words entered in a text box

Counting words entered in a text box cover image
  1. Home
  2. HTML
  3. Counting words entered in a text box

Here is a JavaScript function that counts the number of words typed in a text box. In the next tip we’ll see how to put this function to some good use. The function can be called from the onclick() event of a submit button.

function count_words(tbox_input)
   {
   no_words = tbox_input.value.split(" ");
   alert("Text box has " + no_words.length + " words");
   return false;
   }

The reference to the TEXTAREA is passed as an argument to the function. We then employ the split() method with the space character to split the value of TEXTAREA. The result is an array that is stored in no_words variable. The number of words can now be calculated with the length property of the array data type.

The code for the HTML form is as follows:

<FORM NAME="myform">
<TEXTAREA NAME="details" COLS="30" ROWS="6">
This text box has six words.
</TEXTAREA>
<INPUT TYPE="SUBMIT" VALUE="Check" 
ONCLICK="return count_words(document.myform.details)">
</FORM>

Click here to see how this works!

Note: The text placed between <TEXTAREA> – </TEXTAREA> tags is the value of the text box.

HTML JavaScript