Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set maxlength for multiline TextBox?

When using a MultiLine TextBox (which generates a TextArea) setting the MaxLength property has no effect. What is the best workaround? I'd like to get basic, intended functionality with minimum of ugly javascript etc. Just prevent user from entering more than max number of characters.

like image 776
Timur Sadykov Avatar asked Mar 21 '12 02:03

Timur Sadykov


People also ask

How can set maximum length of TextBox in asp net?

Use the MaxLength property to limit the number of characters that can be entered in the TextBox control. This property is applicable only when the TextMode property is set to TextBoxMode. SingleLine or TextBoxMode. Password .

What is multiline in TextBox?

A multiline text box control is a large text box that can display several lines of text or accept this text from user input. Text boxes are often linked to select value lookups and detailed menus. You can place a multiline text box control within a section control.


3 Answers

If you don't care about older browsers (see supported browsers here),
you can set MaxLength normally like this

<asp:TextBox ID="txt1" runat="server" TextMode="MultiLine" MaxLength="100" />

and force it to be printed out to the HTML

protected void Page_Load(object sender, EventArgs e)
{
  if (!IsPostBack)
    txt1.Attributes.Add("maxlength", txt1.MaxLength.ToString());
}
like image 114
Aximili Avatar answered Sep 22 '22 18:09

Aximili


If you want to let the user know if he exceeded the amount of characters as he writes, you could use a javascript function attached to keypress event. This function would test the length of the input and cancel the character rendering if the maxlenght was reached.

Another option is to use RegularExpressionValidator control to validate the input on submit.

In my opinion, the first option is much more better.

I'm not adding any code since google is full of examples for all tastes, this is a very common task.

Here you have a sample search that might help.

like image 35
Claudio Redi Avatar answered Sep 18 '22 18:09

Claudio Redi


Hey pukipuki you can do as follows:

<asp:TextBox ID="txtValue" runat="server"TextMode="MultiLine" Rows="10"Columns="50"></asp:TextBox>

 $(document).ready(function(){ 
 var MaxLength = 250; 
 $('#txtValue').keypress(function(e) 
 { 
     if ($(this).val().length >= MaxLength)
 {    
    e.preventDefault();
 }  
 });});

You can see more in this following link: http://jquerybyexample.blogspot.in/2010/10/set-max-length-for-aspnet-multiline.html

like image 42
ankit rajput Avatar answered Sep 21 '22 18:09

ankit rajput