0

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!

Tomalak
  • 332,285
  • 67
  • 532
  • 628
Tony
  • 18,776
  • 31
  • 129
  • 193

1 Answers1

3

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'); 
    })
});
Espo
  • 41,399
  • 21
  • 132
  • 159
  • I ended up using this one which looks very close to twitter: http://www.javascriptkit.com/script/script2/enforceform.shtml – Tony Oct 19 '09 at 13:21