views:

191

answers:

2

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!

+2  A: 

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
I ended up using this one which looks very close to twitter: http://www.javascriptkit.com/script/script2/enforceform.shtml
Tony
+1  A: 

Check Here and here

Jim