Sep 19, 2009

Limiting length of Multiline textbox(inside webpart) through javascript

Here the requirement is to limit the maxlength of multiline text box in webpart .This seems to be very simple problem,just set the property of MaxLength property of TextBox to some no,but when somehow this property does not work with Multiline Text Box..may be there will be some fix in future release.

So we fix this problem using java script

Add this javascript in the CreateChildControl method.

Here is javascript for this :

----------------------------------------------------------

StringBuilder javascript = new StringBuilder();

javascript.AppendLine("<script type='text/javascript'>");

javascript.AppendLine("function Validation(evt,maxLength)");

javascript.AppendLine("{");

javascript.AppendLine("if(evt.value.length > maxLength)");

javascript.AppendLine("{");

javascript.AppendLine("alert('Maximum 255 characters allowed');");

javascript.AppendLine("evt.value = evt.value.substring(0,maxLength);");

javascript.AppendLine("}");

javascript.AppendLine("}");

javascript.AppendLine("</script>");

if (javascript != null)

{

Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "javascriptcode", javascript.ToString());

}

-------------------------------------------------------------

In above code we have written the java script and registered the client script in the page.Now we need to add this javascript event in the multiline textbox

-------------------------------------------------------------txtMultilineTextBox.Attributes.Add("onKeyDown", "Validation(this, 255)");

----------------------------------------------------------------
Now we have added the event in the text box for "onKeyDown" event .So whenever user exceed 255 characters in the text box this event will fire and limit the length.

No comments:

Post a Comment