Introduction
ASP.net provides textbox controls for data inputs and they are used vastly on the websites. TextMode='Multiline' property of textbox is used everywhere to input comments or any large data.
With my program assignment I came across a problem to set MaxLength for multiline textbox, i.e after some specified length, the textbox should not accept any characters.
(Note: This solution will only tested & recommended for IE (5+) & Firefox )
Details
The MaxLength property of textbox control works fine if Multiline mode is not set, but if TextMode='Multiline' is set in aspx page then this property is of no use and user can input any number of characters inspite of setting maxlength.
Finally I was able to find a solution and wanted to share it with you all.
This example requires just very basic knowledge
of java script so don’t be scared I promise this will be one of the
easiest java scripts that can solve a complex problem.
Add the following to your Multiline box in aspx page:
<asp:TextBox Rows="5" Columns="80" ID="txtCommentsForSearch" MaxLength="10" onkeyDown="return checkTextAreaMaxLength(this,event,'10');" TextMode="multiLine" CssClass="textArea" runat="server"> </asp:TextBox>
*txtCommentsForSearch-This is asp.net control that is having multiline property set
I have used MaxLength='1999', same property you have to use in underlying javascript file also. I have also passed this length to the calling javascript method, so that in case the MaxLength is not accessible then can be picked from parameters of javascript method.
Add the following to your javascript file:
function checkTextAreaMaxLength(textBox, e, length) {
var mLen = textBox["MaxLength"];
if (null == mLen)
mLen = length;
var maxLength = parseInt(mLen);
if (!checkSpecialKeys(e)) {
if (textBox.value.length > maxLength - 1) {
if (window.event) {
e.returnValue = false;
return false;
}
else e.preventDefault();
}
}
}
function checkSpecialKeys(e) {
if (e.keyCode != 8 && e.keyCode != 46 && e.keyCode != 35 && e.keyCode != 36 && e.keyCode != 37 && e.keyCode != 38 && e.keyCode != 39 && e.keyCode != 40)
return false;
else
return true;
}