Posts Tagged ‘text box’

Easy Text Area Character Counter with Javascript

Saturday, August 16th, 2008

Have you ever wanted to add a character counter to a box of text on a web form, but didn’t want to get your hands dirty with all of the Javascript and programming that’s necessary to make it work? If you said yes, then start getting excited right now.

Recently, I had the need to create a character counter for some text areas on a web form. As many people have come to realize, most browsers don’t enforce a maxlength on text areas. To help handle this, I wrote a little script that finds maxlength attributes on textarea elements. Once they are found it ties the element to a function that will count the characters, and force cut offs if you require it.

Remember, you should always double check your lengths on the server side before you send the values off to wherever they may be going. People can disable Javascript on their browsers to get around the limits you set.

Check out the demo below:


Demonstration Form

Using the code is very simple. All you have to do is include the script into your document’s source, and then attach attributes to your textarea elements like this:


Example Code
<textarea name="fixlength" maxlength="300" lengthcut="true">your text here...</textarea>

You’ll notice two new attributes not usually placed on textarea elements: maxlength and lengthcut. The maxlength attribute makes the code display the character counter. If you add lengthcut="true" the maxlength will be enforced and will not allow users to type past the limit. Check out the full code example below…


Example Code
<form method="post" action="YourScriptHere.php">
<textarea name="getlength" maxlength="300" rows="5" cols="45">Demo Text. This field has a maxlength</textarea>
<textarea name="fixlength" maxlength="300" lengthcut="true" rows="5" cols="45">Demo Text. This field has a maxlength, and the length is enforced.</textarea>
<label></label>
<textarea name="nolength" rows="5" cols="45">This field has no maxlength.</textarea>
<input type="submit" value="Submit" />
</form> <script type="text/javascript" language="javascript" src="/scripts/charcount.js"></script>

Adding extra elements with Javascript on the fly after the page loads? No problem! Simply call the parseCharCounts(); method after your new textarea has been appended to the document. The script to make find then new textarea elements and handle them accordingly.

Ready to use it on your own pages? Download or copy the source now for free!

  • Right click and select to save, or click the link to view or copy the source
  • DOWNLOAD NOW: charcount.js