how to set maxlength for multiline textbox in asp.net
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:
I have used MaxLength='155', 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:
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 ID="txtQuestion"
runat="server"
MaxLength="155"
TextMode="MultiLine"
CssClass="textarea" Style="width: 300px" onkeyDown="checkTextAreaMaxLength(this,event,'155');"
>asp:TextBox> I have used MaxLength='155', 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:
<script type="text/javascript">
function
textboxMultilineMaxNumber(txt,maxLen){
try{
if(txt.value.length
> (maxLen-1))
return
false;
}catch(e){
}
}
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)//IE
e.returnValue = false;
else//Firefox
e.preventDefault();
}
}
}
function
checkSpecialKeys(e)
{
if(e.keyCode
!=8 && e.keyCode!=46 && e.keyCode!=37 && e.keyCode!=38
&& e.keyCode!=39 && e.keyCode!=40)
return false;
else
return true;
}
script>
No comments :
Post a Comment