It is really easy to do this: Newer browsers support the maxlength
attribute on textarea
elements (but not IE9 and older versions of Internet Explorer).
You can limit textarea
with javascript, or at least get the character count if you want to show "x chars remaining" (like posting a comment in SO).
For older browsers this javascript will check the length against the maxlength and prevent user from typing. However, since users can potentially defeat the keydown
approach via copy and paste, etc., it is also a good idea to use keyup
to truncate any overflow. Also, if data is going into the server/database it is not a bad idea to truncate and sanitize the input received from client in case the client bypasses the form and uploads POST data directly in which case maxlength
has no effect.
In ASP.NET the markup looks like: <asp:TextBox ID="txt" runat="server" TextMode="Multiline" ClientIDMode="Static" maxlength="150"/>
but for textarea
(TextMode="Multiline") the maxlength
attribute may not be rendered (perhaps depending on your ASP.NET version). You can verify in the markup whether it was rendered. If not, you may need to manipulate the TextBox's Attributes
in the codebehind like this: txt.Attributes["maxlength"] = "150";
(assuming C#)
JS Fiddle example: http://jsfiddle.net/aymjsfdp/
// "maxlength" code for older browsers including IE9 and previous versions
var txt = document.getElementById('txt');
txt.onkeyup = function () {
var maxlength = parseInt(this.getAttribute("maxlength")) || 0;
if (maxlength > 0 && this.value.length > maxlength) {
this.value = this.value.substring(0, maxlength);
alert('text was truncated to ' + maxlength + ' characters.');
}
document.getElementById('length').innerHTML = this.value.length.toString();
};
txt.onkeydown = function () {
var maxlength = parseInt(this.getAttribute("maxlength")) || 0;
if (maxlength > 0 && this.value.length >= maxlength && (event.keyCode || event.which) > 49) {
return false;
}
};
TEXTAREA {
width: 300px;
height: 60px;
}
<div>Chars: <span id='length'></span>
</div>
<textarea id='txt' maxlength='150'></textarea>