I\'m trying to use asp:
I want a way to spe
try this javascript:
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;
}
On the control invoke it like this:
<asp:TextBox Rows="5" Columns="80" ID="txtCommentsForSearch" MaxLength='1999' onkeyDown="checkTextAreaMaxLength(this,event,'1999');" TextMode="multiLine" runat="server"> </asp:TextBox>
You could also just use the checkSpecialKeys function to validate the input on your javascript implementation.
keep it simple. Most modern browsers support a maxlength attribute on a text area (IE included), so simply add that attribute in code-behind. No JS, no Jquery, no inheritance, custom code, no fuss, no muss.
VB.Net:
fld_description.attributes("maxlength") = 255
C#
fld_description.Attributes["maxlength"] = 255
$("textarea[maxlength]").on("keydown paste", function (evt) {
if ($(this).val().length > $(this).prop("maxlength")) {
if (evt.type == "paste") {
$(this).val($(this).val().substr(0, $(this).prop("maxlength")));
} else {
if ([8, 37, 38, 39, 40, 46].indexOf(evt.keyCode) == -1) {
evt.returnValue = false;
evt.preventDefault();
}
}
}
});
Roll your own:
function Count(text)
{
//asp.net textarea maxlength doesnt work; do it by hand
var maxlength = 2000; //set your value here (or add a parm and pass it in)
var object = document.getElementById(text.id) //get your object
if (object.value.length > maxlength)
{
object.focus(); //set focus to prevent jumping
object.value = text.value.substring(0, maxlength); //truncate the value
object.scrollTop = object.scrollHeight; //scroll to the end to prevent jumping
return false;
}
return true;
}
Call like this:
<asp:TextBox ID="foo" runat="server" Rows="3" TextMode="MultiLine" onKeyUp="javascript:Count(this);" onChange="javascript:Count(this);" ></asp:TextBox>
Use HTML textarea with runat="server"
to access it in server side.
This solution has less pain than using javascript or regex.
<textarea runat="server" id="txt1" maxlength="100" />
Note: To access Text
Property in server side, you should use txt1.Value
instead of txt1.Text
you can specify the max length for the multiline textbox in pageLoad Javascript Event
function pageLoad(){
$("[id$='txtInput']").attr("maxlength","10");
}
I have set the max length property of txtInput multiline textbox to 10 characters in pageLoad() Javascript function