Helping ordinary people create extraordinary websites!
GET OUR NEWSLETTER
Your Email:
 

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


 | Bookmark
Related Tutorials:
» JavaScript Debugging Techniques with Firebug
» Striped Tables Using JavaScript
» Opening PDFs in a New Window with JavaScript
» Essential Javascript -- A Javascript Tutorial
» Submit Forms Conditionally using JavaScript
» How to Setup a Randomising Function

Advertise with Us!


Tutorials Scripts Web Hosting Developer Manuals
Resources