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>