Apply limit function in all textareas

2

I am imposing limit of characters in my textareas manually with this code:

<textarea onKeyDown="limitText(this.form.message,this.form.countdown,240);" 
onKeyUp="limitText(this.form.message,this.form.countdown,240);"></textarea>

But I came to the conclusion that it is dirty and takes up space. I would like to use jQuery to be able to apply this limitText(this.form.message,this.form.countdown,240); function to all existing textareas on my site.

The function limitText is this

function limitText(limitField, limitCount, limitNum) {
if (limitField.value.length > limitNum) {
    limitField.value = limitField.value.substring(0, limitNum);
} else {
    $("#countdown").html(limitField.value.length);
}
}
    
asked by anonymous 12.12.2014 / 23:44

1 answer

3

Currently, with HTML5 you do not need to use scripts to limit the amount of characters in a <textarea> , you can only use the maxlength :

<textarea maxlength='240'></textarea>

Original answer:

Your limitText fault function can have only two parameters:

function limitText(limitField, limitNum){
   var content = "" + $(limitField).val(); // pega o valor na textarea.
   return content.length > limitNum ? content.substr(0, limitNum) : content;
}

In addition to the events keyup and keydown , it would be good to listen to keypress also, to do the verification even if the user keeps a key pressed.

$("textarea").bind("keypress keyup keydown", function(){
  $(this).val(limitText($(this), 240));
});

textarea {width: 300px;border:2px solid #ccc}
<textarea placeholder="Limite de caracteres: 240"></textarea>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script><script>$(function(){$("textarea").bind("keypress keyup keydown", function(){
      $(this).val(limitText($(this), 240));
    });
    
    function limitText(limitField, limitNum){
      var content = "" + $(limitField).val();
      return content.length > limitNum ? content.substr(0, limitNum) : content;
    }
  });
</script>
    
13.12.2014 / 09:06