Text Area Counter

30 July 2004 16:46

Something that I’ve seen on other sites, particularly online SMS sending tools, is form textarea’s that have a little box telling you how many characters you’ve typed, or that you have left to enter.

It’s not that tricky to setup really. You need a form with a textarea, and a very simple Javascript function to count the code.

/* javascript function to update form field
* field      form field that is being counted
* count      form field that will show characters left
* maxchars    maximum number of characters   
*/
function characterCount(field, count, maxchars) {
   if (field.value.length > maxchars) {
      field.value = field.value.substring(0, maxchars);
      alert(“Error:

- You are only allowed to enter up to “
+maxchars+” characters.”);
   } else {
      count.value = maxchars – field.value.length;
   }
}

The textarea needs a couple of event handlers so it knows to do something:

<textarea name=“notes” cols=“40″ rows=“5″ wrap=“virtual” onKeyDown=“characterCount(this.form.notes,this.form.remaining,255);”
onKeyUp=“characterCount(this.form.notes,this.form.remaining,255);”>
</textarea>

The full code can be seen or you can view the demo.

Filed: Technology // Tagged:

You can follow any responses to this entry through the RSS 2.0 feed.

You can leave a comment or leave a trackback from your own site.

Leave a Reply

 
What's ianteresting?   •   Twitter   •   About   •   Contact
©2012 Ian Winter. All Rights Reserved.   •   Powered by WordPress   •   Hosted at Memset