Javascript onkeyup keypress event to check max length of HTML textarea C# VB.Net

In many forums i found that Asp.Net C# VB.Net developers ask how to check max length of textarea HTML control. That’s why i think I will post this topic. This article also resolve cross browser issue as well as copy paste problem in clipboard. In my previous post i have explained “How to setting up TextBox max length using javascript onkeyup keypress event“. In this article i will explain the same thing but for HTML textarea. Because lot reasons for developers to use HTML textarea instead of TextBox. It will restrict user within your Max Length limit.

The Output:

Javascript Max Length Function Code Example for HTML textarea:

<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').innerText = objTxtCtrl.value.length + ' Out Of ' + nLength;
            document.getElementById('lblCaption').textContent = objTxtCtrl.value.length + ' Out Of ' + nLength;


The HTML textarea to Invoke the Javascript Method:

<textarea rows="5" cols="50" onkeyup="return ismaxlength(this,125)"></textarea>
<br />
<label id='lblCaption' style="font-family:Tahoma;font-size:1em;font-weight:bold"></label>

Note: You can adjust the 2nd parameter of ismaxlength() method to increase or decrease the Max Length.

Hope now you can apply Max Length property in textarea control.

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

Download Code Example C#        Download Code Example VB.Net
Download Code Example Plain HTML

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

Leave a Reply

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