tags:

views:

64

answers:

4

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  A: 

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);

   }           
});
patrick dw
A: 
$(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/

griegs
+1  A: 
​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

Tanguy
A: 

I can only think of the "return false " mothod. thank you

keepyouliking