22 November 2008

How to Set MaxLength of a Multiline TextBox

Ever tried setting up the maxlength property of a ASP.NET Multiline TextBox and ended up finding out that its doesn't work at all!! HEre's a simple solution using Javascript..
You can use the below script to set up the maxlength of a Multiline TextBox or even a HTML TextArea Tag:

<script type="text/javascript" language="javascript">

function ismaxlength(obj){
var mlength=obj.getAttribute? parseInt(obj.getAttribute("maxlength")) : ""
if (obj.getAttribute && obj.value.length>mlength)

Inside any textarea you wish to add a "maxlength" attribute to, simply do the following:

<textarea maxlength="40" onkeyup="return ismaxlength(this)" ></textarea>
<asp:TextBox ID="txt1" runat="server" maxlength="40" onkeyup="return ismaxlength(this)" />

The part in green is what you should add, with "40" obviously being the maximum number of characters accepted by this textarea.
Note: In ASP.NET setting up the maxlength might not work. Hence you should replace the textbox with a textarea and run it as a server control using runat="server"

No comments: