How to impose maxlength on textArea in HTML using JavaScript

Rakesh Juyal picture Rakesh Juyal · Jul 14, 2009 · Viewed 236.7k times · Source

I would like to have some functionality by which if I write

<textarea maxlength="50"></textarea>
<textarea maxlength="150"></textarea>
<textarea maxlength="250"></textarea>

it will automatically impose the maxlength on the textArea. If possible please do not provide the solution in jQuery.

Note: This can be done if I do something like this:

<textarea onkeypress="return imposeMaxLength(event, this, 110);" rows="4" cols="50">

function imposeMaxLength(Event, Object, MaxLen)
{
    return (Object.value.length <= MaxLen)||(Event.keyCode == 8 ||Event.keyCode==46||(Event.keyCode>=35&&Event.keyCode<=40))
}

Copied from What is the best way to emulate an HTML input “maxlength” attribute on an HTML textarea?

But the point is I don't want to write onKeyPress and onKeyUp every time I declare a textArea.

Answer

Josh Stodola picture Josh Stodola · Jul 14, 2009
window.onload = function() { 
  var txts = document.getElementsByTagName('TEXTAREA'); 

  for(var i = 0, l = txts.length; i < l; i++) {
    if(/^[0-9]+$/.test(txts[i].getAttribute("maxlength"))) { 
      var func = function() { 
        var len = parseInt(this.getAttribute("maxlength"), 10); 

        if(this.value.length > len) { 
          alert('Maximum length exceeded: ' + len); 
          this.value = this.value.substr(0, len); 
          return false; 
        } 
      }

      txts[i].onkeyup = func;
      txts[i].onblur = func;
    } 
  };

}