Please enable JavaScript to view this site.

iService Forms User Guide

Navigation: HTML Snippets and Examples

Limit Number of Characters in a Form Field

Scroll Prev Top Next More

This little JavaScript has been very useful. Thanks to http://www.mediacollege.com/internet/javascript/form/limit-characters.html for nice tight code.

 

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:

 

Step 1 - Create Function for Head

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 - Use -customHTML in the Form Body

Use the following code to create the text area (change the name of the text area to suit your needs):

 

$input -id'limitedtextarea' -customHTML$

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

 

(Note: replace "LimitedTextArea" with the id of your form item)

 

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

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

 

The result looks like this:

LimitFieldLength

 

 

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.