Wednesday, July 28, 2010

ASP.Net: Maximum length of textarea (Multiline textbox)

In ASP.Net if we use textbox with TextMode="MultiLine" then its MaxLength property does not work. There is a simple workaround for it using javascript.

First dd the javascript function. This will restrict the textbox to maximum of 10 characters. As the user start typing the 11th character it will remove the 11th character immediately.

<script type="text/javascript"> 
function CheckMaxLength(txtBoxVal) {
        if (txtBoxVal.value.length > 10) {
            txtBoxVal.value = txtBoxVal.value.substring(0, 10);
        }
    }

</script>

Then add the function to onkeyup event of textbox. (Intellisence will not show onkeyup event in visual studio you have to type it yourself)

<asp:TextBox ID="txtName" TextMode="MultiLine" Height="50px" runat="server" Rows="3"  onkeyup="CheckMaxLength(this);" ></asp:TextBox>
Enjoy coding.... ! :)

No comments:

Post a Comment