Thursday, September 10, 2009

Limit the number of characters in the Asp.Net TextArea

This tips will help you to limit the number of characters in the Asp.Net TextArea or Asp.Net Multiline Textbox. It uses a JavaScript function to limit the characters keyed in the TextArea.

Step 1: Add the below JavaScrpit function between the in your aspx page.

function fnLimitTextAreaChars(textareaName, NoOfChars)
{
if (textareaName.value.length > NoOfChars)
{
textareaName.value = textareaName.value.substring(0, NoOfChars);
}
}

Step 2: In the code-behind at Page_Load event, add the two lines as follows.

TextBox1.Attributes.Add(”onKeyDown”, “fnLimitTextAreaChars(this, 150)”);
TextBox1.Attributes.Add(”onKeyUp”, “fnLimitTextAreaChars(this, 150)”);

It’s done. Now when you type any letters in the TextArea, it will allow only first 150 characters. The rest will be truncated. Try yourself.

No comments:

Post a Comment