textarea character limit

Web_Designer picture Web_Designer · Apr 4, 2011 · Viewed 115k times · Source

I would like to be able to limit the number of characters in a textarea. The method I am using works great in Google Chrome, but is slow in Firefox, and doesn't work in IE.

Javascript:

function len(){
  t_v=textarea.value;
  if(t_v.length>180){
    long_post_container.innerHTML=long_post;
    post_button.className=post_button.className.replace('post_it_regular','post_it_disabled');
    post_button.disabled=true;
  }
  else{
    long_post_container.innerHTML="";
    post_button.className=post_button.className.replace('post_it_disabled','post_it_regular');
    post_button.disabled=false;
  }
  if(t_v.length>186){
        t_v=t_v.substring(0,186);
    }
}

HTML:

<textarea id="user_post_textarea" name="user_post_textarea" cols="28" rows="1"  onkeypress="len();" onkeyup="len();"></textarea>

Javascript at bottom of body element:

textarea=document.getElementById('user_post_textarea');

Answer

Web_Designer picture Web_Designer · Apr 9, 2011

I found a good solution that uses the maxlength attribute if the browser supports it, and falls back to an unobtrusive javascript pollyfill in unsupporting browsers.

Thanks to @Dan Tello's comment I fixed it up so it works in IE7+ as well:

HTML:

<textarea maxlength="50" id="text">This textarea has a character limit of 50.</textarea>

Javascript:

function maxLength(el) {    
    if (!('maxLength' in el)) {
        var max = el.attributes.maxLength.value;
        el.onkeypress = function () {
            if (this.value.length >= max) return false;
        };
    }
}

maxLength(document.getElementById("text"));

Demo

There is no such thing as a minlength attribute in HTML5.
For the following input types: number, range, date, datetime, datetime-local, month, time, and week (which aren't fully supported yet) use the min and max attributes.