views:

2443

answers:

3

I'm trying to use asp:

<asp:TextBox ID="txtInput" runat="server" TextMode="MultiLine"></asp:TextBox>

and i want a way to specify the maxlength property ,but apparently there is not such for multiline textbox. I've been trying to use some javascript for the onkeypress event onkeypress="return textboxMultilineMaxNumber(this,maxlength)"

function textboxMultilineMaxNumber(txt, maxLen) {
            try {
                if (txt.value.length > (maxLen - 1)) return false;

            } catch (e) {
            }
            return true;
        }

while working fine the problem with this javascript function is that after writing characters it doesn't allow you to delete and substitute any of them, such a behavior is not desired.

Have you got any idea what can i possibly change in the above code to avoid that or any other ways to get round it. Thank you!!

+2  A: 

Hi, 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.

Raúl Roa
Thank you it works fine! Great really!!!
Izabela
This is great except that the limiting fails when the user enters carriage returns. Carriage returns don't add anything to javascript's value.length count but do contribute to the overall size of the string ('\n' is two characters). If your server is limiting the string size, you'll still get truncation whenever someone uses carriage returns.
Mr Grieves
My last comment only seems to apply to certain browsers. IE returns a proper length value (including carriage return characters). Webkit does not.
Mr Grieves
+1  A: 

Have a look at this. The only way to solve it is by javascript as you tried.

EDIT: Try changing the event to keypressup.

Christian13467
A: 

you might be trying to run the function in firefox run it in IE it will work..

Prashant