Tony
Tony

Reputation: 19181

How to limit the size of an HTML textarea with JavaScript?

Anyone have code to limit the characters in a text field and display the character count?

I need something like twitter status input and I can't find anything online. If there isn't anything out there, I'll probably make a jQuery plugin or at least open source this thing.

Thanks!

Upvotes: 0

Views: 1928

Answers (1)

Espo
Espo

Reputation: 41949

Take a look at this page:

Interactive character limit for textarea using Jquery

 <script language="javascript">
 function limitChars(textid, limit, infodiv)
 {
     var text = $('#'+textid).val(); 
     var textlength = text.length;
     if(textlength > limit)
     {
         $('#' + infodiv).html('You cannot write more then '+limit+' characters!');
          $('#'+textid).val(text.substr(0,limit));
          return false;
     }
     else
     {
      $('#' + infodiv).html('You have '+ (limit - textlength) +' characters left.');
      return true;
     }
 }
 </script>

Then bind the function to the keyup event of your textarea. Do this in jQuery’s ready event of document like this:

$(function(){
    $('#comment').keyup(function()
    { 
        limitChars('comment', 20, 'charlimitinfo'); 
    })
});

Upvotes: 3

Related Questions