Javascript onkeyup keypress event to check max length of a Multiline Textbox Asp.Net C# VB.Net

Most of the developers assume that maxlength property of a Textbox will work even the Multiline property set to true. But the reality is, it does not work. To check or restrict maxlength of a Multiline Textbox, you have to develop your own javascript fucntion. In this article I will show you how you can limit or restrict Multiline Textbox character limit using javascript method onkeyup.

Desired Output:
Javascript_onkeyup_keypress_event_to_check_max_length_of_a_Multiline_Textbox_ Asp.Net_ Csharp_VB.Net

Javascript Function Code:

<script type="text/javascript">
    function ismaxlength(objTxtCtrl, nLength) {
        if (objTxtCtrl.getAttribute && objTxtCtrl.value.length > nLength)
            objTxtCtrl.value = objTxtCtrl.value.substring(0, nLength)

        if (document.all)
            document.getElementById('<%= lblCaption.ClientID %>').innerText = objTxtCtrl.value.length + ' Out Of ' + nLength;
            document.getElementById('<%= lblCaption.ClientID %>').textContent = objTxtCtrl.value.length + ' Out Of ' + nLength;


Asp.Net Multiline TextBox Client side onkeyup Event to Invoke the Javascript Method:

<asp:TextBox ID="txtMultiline" runat="server" Rows="5" Columns="50" TextMode="MultiLine" onkeyup="return ismaxlength(this,255)" ></asp:TextBox>    
<br />
<asp:Label runat="server" ID="lblCaption" Font-Bold="true"></asp:Label>

Note: Here i have used the Label “lblCaption” to keep the character count. If you want to increase or decrease the character length adjust ismaxlength() caller method 2nd parameter accordingly.

Now combined everything & run the example, hope you can find your desired output.

Script tested for:
1. Internet Explorer
2. Mozilla Firefox
3. Opera
4. Google Chrome

Download Code Example C#        Download Code Example VB.Net

Posted in, C#, Client, Javascript, VB.Net

Leave a Reply

Your email address will not be published. Required fields are marked *