Helping ordinary people create extraordinary websites!

Limiting Text In Textarea Form Field

By Will Bontrager
2005-05-22

Limiting Text In Textarea Form Field

In certain situations (classified ad, page description, security), you may want to limit the amount of text that can be put into a textarea form field. For regular input tags, you can use the maxlength attribute, but the textarea tag has no such built-in limit specifier.

JavaScript can be used to limit the length.

First, put this somewhere on your page, in the <head></head> area or the <body></head> area, it doesn't really matter:

<script language="JavaScript"><!--

function Trim(s) {
var maxlength = 135; // Change number to your max length.
if (s.value.length > maxlength)
s.value = s.value.substring(0,maxlength);
} // -->
</script>

(Notice where you change the number to set your own maximum character length.)

Last, in the textarea tag, put this short JavaScript code:

onChange="Trim(this.form.message)"

(The "message" is the value in the name="______" of your textarea tag — if yours has a different name, change the above.)

Your textarea might look something like this:

<textarea name="message" wrap="soft" cols="22" rows="5" 

onChange="Trim(this.form.message)"></textarea>

The JavaScript function does not prevent typing more characters than are allowed. But when the user clicks somewhere else, the excess characters are immediately trimmed from the textarea.





Tutorial pages:
  • Limiting Text In Textarea Form Field

Copyright 2004 Bontrager Connection, LLC


 1 Votes

You might also want to check these out:


Leave a Comment on "Limiting Text In Textarea Form Field"
You must be logged in to post a comment.

Link to This Tutorial Page!


GET OUR NEWSLETTERS