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!

1

1 Answer 1

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'); 
    })
});
Sign up to request clarification or add additional context in comments.

1 Comment

I ended up using this one which looks very close to twitter: javascriptkit.com/script/script2/enforceform.shtml

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.