///Limiting Text In Textarea Form Field

Limiting Text In Textarea Form Field

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);
} // -->

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

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


(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" 


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.

2010-05-26T11:11:13+00:00 May 22nd, 2005|JavaScript|0 Comments

About the Author:

Leave A Comment