1. Tech

Your suggestion is on its way!

An email with a link to:


was emailed to:

Thanks for sharing About.com with others!

Limiting Textarea Text

2. The Script

Join the Discussion

Questions? Comments?

More of this Feature


What we are actually doing is using the onkeyup javascript method to execute a javascript every time your visitor presses and releases a key on their keyboard (so that the input gets tested after every key press and not just after your visitor has finished writing a two thousand word essay in the field). This calls a javascript function that tests the length of the field and compares it to the maximum size that we specify and when that size is reached or exceeded the appropriate action is taken.

To start with, here's the code for our textarea field:

<textarea cols="20" rows="2" value=""
onkeyup="textLimit(this, 40);"></textarea>

This passes the current text area field along with a character limit (in this case 40) to a function called textLimit. It is this function which creates the nice effect of having the maximum field size match the size of the field. If you use a different value for the second argument then that will be used as the maximum field size and your visitor will either be unable to fill the complete field (if you make it smaller) or the field will be scrollable (if you make it bigger).

So now let's move on to look at the javascript function. Here's the code that you need to add to the head section of your page in order for the field length restriction to be applied:

function textLimit(field, maxlen) {
if (field.value.length > maxlen + 1)
alert('your input has been truncated!');
if (field.value.length > maxlen)
field.value = field.value.substring(0, maxlen);

The two lines that are not in bold produce the message that is displayed when your visitor tries pasting something into the field and more than one character is lost when the field is truncated. This let's your visitor know that what they have tried to paste has made the content of the field much larger than is allowed and that the excess will be truncated. If you don't want a message in this instance then just omit these two lines.

Sample Page | The Script
See More About

©2016 About.com. All rights reserved.