Question: This html form and the related php code works pretty well together. I need to add a word counter. Any suggestions. 

```
<form action="form.php" method="POST">

<fieldset>

   <input type="hidden" name='counter' value='2'/>

  <p><label for="heading1"></label>
  <input type="text" name="heading1" size="60" /></p>
  <p><label for="input1"></label>   
   <textarea cols="width" rows="height" name="input1">...</textarea></p>

   <p><label for="heading2"></label>
   <input type="text" name="heading2" size="60" value="first para title..."></p>
   <p><label for="input2"></label>
   <textarea cols="width" rows="height" name="input2">...</textarea></p>

<br />
<fieldset>
<input type="submit" value="" />
<input type="reset" value="" />
</fieldset>
</form>

```

The related php code is found below.

```
<?php

$count=$_REQUEST['counter'];

for($i=1;$i<=$count;$i++)
{
echo "<p>" . $_REQUEST['heading'.$i] . "</p>";
echo "<p>" . $_REQUEST['input'.$i]. "</p>";
}

?>  

```

Answer: 
Like this:

```
var output = document.getElementById("counter"),
textarea = document.getElementById("textarea");

 textarea.onkeyup = function (event) {
     var words = textarea.value.split(" ");
     output.value = words.length;
 };

```

To make it easier, add IDs to your HTML elements like this:

```
 <input type="hidden" name="counter" id="counter" value="0"/>
 <textarea cols="width" rows="height" name="input2" id="textarea">...</textarea>

```

What this does: Every time the user releases types a letter into the textarea it will take the contents, split it on spaces and counts the number of words which is inserted into your hidden `counter` field. When the form is submitted the number of words will also be sent to the server.

However, if you don't need the number of words in the client (for instance showing the user how many words she has typed) then I suggest you do this in PHP. Look at the `str_split` function.
Example:

```
<textarea name="input1" onkeyup="window.alert(document.getElementsByName('input1')[0].value.trim().split(' ').length);"></textarea>

```