0

I want to prevent the user from entering more than 100 characters into a textarea. I already wrote the code that will detect when the user's post reaches 100 characters. But I have no idea how to prevent him from typing any more beyond that point:

$(document).ready(function(){

   $('.comment').keyup(function(){
       var count = this.value.length;
       if (count > 100) {

           // what goes here???

       }           
   });

});


  <textarea class="comment" rows="10" cols="30"></textarea>
2
  • you should have server side validation of this too, obviously :D Commented Sep 2, 2010 at 1:38
  • 2
    what if you hold down a keyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy? Commented Sep 2, 2010 at 2:07

3 Answers 3

3

Using keypress may be nicer. You could just return false;

​$('textarea').keypress(function() {
    if(this.value.length >= 100) 
        return false;
})​​​​​;​

This also prevents the user from holding down a key to enter several characters beyond the limit.

If you want to use keyup, you could do this:

$('.comment').keyup(function(){
   var count = this.value.length;
   if (count > 100) {

    this.value = this.value.substr(0,100);

   }           
});
Sign up to request clarification or add additional context in comments.

Comments

1
​jQuery('textarea').keypress(function(e) {
    if(this.value.length >= 100) {
        e.preventDefault();
        return false;
    }
})​​​​​;​

preventDefault is needed for some browsers like IE and supported by all; but really needed only for a href onclick

keyup is not the good event to prevent keys... key repeat is made with keydown

Comments

0
$(document).ready(function(){
    $('textarea[maxlength]').keyup(function(){
        var max = parseInt($(this).attr(’maxlength’));
        if($(this).val().length > max){
            $(this).val($(this).val().substr(0, $(this).attr('maxlength')));
        }

        $(this).parent().find('.charsRemaining').html('You have ' + (max - $(this).val().length) + ' characters remaining');
    });
});

From http://that-matt.com/2008/07/textarea-maxlength-with-jquery/

There is also a plugin for this http://remysharp.com/2008/06/30/maxlength-plugin/

Comments

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.