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>

good and simple code
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….
This code doesn’t account for a user copying and pasting into the field.
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.
I had to use onkeyup instead of onkeypress and then it works even when doing a copy paste.