[html] Set maxlength in Html Textarea

How can I set the maxlength in a textarea? And why maxlength is not working properly in textarea?

This question is related to html input textarea

The answer is


If you are using HTML 5, you need to specify that in your DOCTYPE declaration.

For a valid HTML 5 document, it should start with:

<!DOCTYPE html>

Before HTML 5, the textarea element did not have a maxlength attribute.

You can see this in the DTD/spec:

<!ELEMENT TEXTAREA - - (#PCDATA)       -- multi-line text field -->
<!ATTLIST TEXTAREA
  %attrs;                              -- %coreattrs, %i18n, %events --
  name        CDATA          #IMPLIED
  rows        NUMBER         #REQUIRED
  cols        NUMBER         #REQUIRED
  disabled    (disabled)     #IMPLIED  -- unavailable in this context --
  readonly    (readonly)     #IMPLIED
  tabindex    NUMBER         #IMPLIED  -- position in tabbing order --
  accesskey   %Character;    #IMPLIED  -- accessibility key character --
  onfocus     %Script;       #IMPLIED  -- the element got the focus --
  onblur      %Script;       #IMPLIED  -- the element lost the focus --
  onselect    %Script;       #IMPLIED  -- some text was selected --
  onchange    %Script;       #IMPLIED  -- the element value was changed --
  %reserved;                           -- reserved for possible future use --
  >

In order to limit the number of characters typed into a textarea, you will need to use javascript with the onChange event. You can then count the number of characters and disallow further typing.

Here is an in-depth discussion on text input and how to use server and client side scripting to limit the size.

Here is another sample.


Before HTML5 it's only possible to check this with JavaScript or by a server-side verification (better, because JavaScript obviously only works with JavaScript enabled...). There is no native max-length attribute for textareas.

Since HTML5 it's a valid attribut, so defining your doctype as HTML5 may help. I don't know if all browsers support this attribute, though:

<!DOCTYPE html>

As I said in a comment to aqingsao's answer, it doesn't quite work when the textarea has newline characters, at least on Windows.

I've change his answer slightly thus:

$(function() {
    $("textarea[maxlength]").bind('input propertychange', function() {
        var maxLength = $(this).attr('maxlength');
        //I'm guessing JavaScript is treating a newline as one character rather than two so when I try to insert a "max length" string into the database I get an error.
        //Detect how many newlines are in the textarea, then be sure to count them twice as part of the length of the input.
        var newlines = ($(this).val().match(/\n/g) || []).length
        if ($(this).val().length + newlines > maxLength) {
            $(this).val($(this).val().substring(0, maxLength - newlines));
        }
    })
});

Now when I try to paste a lot of data in with newlines, I get exactly the right number of characters.


<p>
   <textarea id="msgc" onkeyup="cnt(event)" rows="1" cols="1"></textarea> 
</p> 
<p id="valmess2" style="color:red" ></p>

function cnt(event)
{ 
 document.getElementById("valmess2").innerHTML=""; // init and clear if b < max     
allowed character 

 a = document.getElementById("msgc").value; 
 b = a.length; 
 if (b > 400)
  { 
   document.getElementById("valmess2").innerHTML="the max length of 400 characters is 
reached, you typed in  " + b + "characters"; 
  } 
}

maxlength is only valid for HTML5. For HTML/XHTML you have to use JavaScript and/or PHP. With PHP you can use strlen for example.This example indicates only the max length, it's NOT blocking the input.


try this

$(function(){
  $("textarea[maxlength]")
    .keydown(function(event){
       return !$(this).attr("maxlength") || this.value.length < $(this).attr("maxlength") || event.keyCode == 8 || event.keyCode == 46;
    })
    .keyup(function(event){
      var limit = $(this).attr("maxlength");

      if (!limit) return;

      if (this.value.length <= limit) return true;
      else {
        this.value = this.value.substr(0,limit);
        return false;
      }    
    });
});

For me works really perfect without jumping/showing additional characters; works exactly like maxlength on input


simple way to do maxlength for textarea in html4 is:

<textarea cols="60" rows="5" onkeypress="if (this.value.length > 100) { return false; }"></textarea>

Change the "100" to however many characters you want


$(function(){  
  $("#id").keypress(function() {  
    var maxlen = 100;
    if ($(this).val().length > maxlen) {  
      return false;
    }  
  })
});  

resize:none; This property fix your text area and bound it. you use this css property id your textarea.gave text area an id and on the behalf of that id you can use this css property.


Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to input

Angular 4 - get input value React - clearing an input value after form submit Min and max value of input in angular4 application Disable Button in Angular 2 Angular2 - Input Field To Accept Only Numbers How to validate white spaces/empty spaces? [Angular 2] Can't bind to 'ngModel' since it isn't a known property of 'input' Mask for an Input to allow phone numbers? File upload from <input type="file"> Why does the html input with type "number" allow the letter 'e' to be entered in the field?

Examples related to textarea

Get user input from textarea Set textarea width to 100% in bootstrap modal Remove scrollbars from textarea Add a scrollbar to a <textarea> Remove all stylings (border, glow) from textarea How to clear text area with a button in html using javascript? Get value from text area What character represents a new line in a text area Count textarea characters More than 1 row in <Input type="textarea" />