Set Textarea Maxlength with JavaScript Intrinsic Events

With the wonderful implementations of AJAX, many people (myself included) tend to look first within libraries like Dojo when trying to implement a client-side solution. While this is generally a good approach, one thing that some developers tend to forget is the intrinsic events like onkeypress, onmouseout, etc.

A good example is the textarea tag. It doesn’t have any limit on the number of characters like the input tag, so it’s a great candidate for a simple JavaScript function to duplicate the maxlength functionality. The initial instinct when coding something to handle this is to check the length of the field and return a false if it’s reached the limit. This does indeed limit the size, but there’s one problem; backspace and delete trigger onkeypress. As a result, if you’re at the limit and try to delete characters, it returns false and nothing happens! Instead, I find the best solution is to truncate the field if the size is reached. For example, to limit a textarea to 255 characters:

<textarea id="maxdemo" rows="20" cols="80"
 onkeypress="maxlength(this, 255);"></textarea>
<script type="text/javascript">
<!--
/**
 * Determines if a field is exceeding the maximum size
 * and truncates the string if it is over the limit.
 */
function maxlength(field, size) {
    if (field.value.length > size) {
        field.value = field.value.substring(0, size);
    }
}
// -->
</script>

5 thoughts on “Set Textarea Maxlength with JavaScript Intrinsic Events

  1. The following code will do the same thing.

    The only problem with your code and mine is that the maxlength function will not work with copy paste. You’ll be able to copy any string into it….

  2. Yeah, good point. There are always things that users can do on the client side to get around validation, especially with tools like Firebug. We include stuff like this in JavaScript as a first line of defense, but always make sure to do validation on the server too.

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>