Home : Internet : JavaScript : Limit Textarea

Limit the Number of Characters in a Textarea or Text Field

This script allows you to set a limit on the number of characters a user can enter into a textarea or text field, like so:


(Maximum characters: 100)
You have characters left.

Step 1 - Create Function

Insert the following code into the page head:

<script language="javascript" type="text/javascript">
function limitText(limitField, limitCount, limitNum) {
	if (limitField.value.length > limitNum) {
		limitField.value = limitField.value.substring(0, limitNum);
	} else {
		limitCount.value = limitNum - limitField.value.length;
	}
}
</script>

Step 2 - Create Text Area

Use the following code to create the form and text area (if necessary, change the name of the form and text area to suit your needs):

<form name="myform">
<textarea name="limitedtextarea" onKeyDown="limitText(this.form.limitedtextarea,this.form.countdown,100);" 
onKeyUp="limitText(this.form.limitedtextarea,this.form.countdown,100);">
</textarea><br>
<font size="1">(Maximum characters: 100)<br>
You have <input readonly type="text" name="countdown" size="3" value="100"> characters left.</font>
</form>

To create a single-line text field instead of a text area, use the following code:

<form name="myform">
<input name="limitedtextfield" type="text" onKeyDown="limitText(this.form.limitedtextfield,this.form.countdown,15);" 
onKeyUp="limitText(this.form.limitedtextfield,this.form.countdown,15);" maxlength="15"><br>
<font size="1">(Maximum characters: 15)<br>
You have <input readonly type="text" name="countdown" size="3" value="15"> characters left.</font>
</form>

The result looks like this:


(Maximum characters: 15)
You have characters left.

Note: You can have multiple text areas and/or fields on the same page using the same function. Just make sure you give each field a unique name.