Limit amount of input in a field

Jake Howlett, 3 November 2000

Category: Forms; Keywords: input length limit

Have you ever created a form with a field on it that relies on the user entering a "short description" and then had that nagging feeling, knowing that they can enter as much text as they like? This script will help.

The field below has been limited to 125 characters. Try typing more than that and see what happens:



characters left.

The JavaScript function required is:

<script type="text/JavaScript">
<!--
function textCounter(field, maxlimit) {
if (field.value.length > maxlimit)
field.value = field.value.substring(0, maxlimit);
}
-->
</script>


All you need then is to place calls to it in the onKepUp and onKeyDown events for a field.

<textarea name="message" onKeyDown="textCounter(this.form.message, 125);" onKeyUp="textCounter(this.form.message, 125);"></textarea>


Note: If you want to include the field that has the number of characters remaining as well, take a look at the source to this page.

Also note that, as with most solutions, there are the loop-holes. This method does not stop the user from pasting a load of text in to the field by right-clicking and selecting Paste. Thus, bypassing the onKeyUp/Down events. You still need validation if the restriction is anything more than advisory.