Apply limit function to all textareas

Asked

Viewed 62 times

2

I am manually imposing character limit on my textareas 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 soils and occupies space. I would like to turn to jQuery to apply this function limitText(this.form.message,this.form.countdown,240); in all textareas existing on my website.

the function limitText that’s the one

function limitText(limitField, limitCount, limitNum) {
if (limitField.value.length > limitNum) {
    limitField.value = limitField.value.substring(0, limitNum);
} else {
    $("#countdown").html(limitField.value.length);
}
}

1 answer

3


Currently, with HTML5 it is not necessary to use scripts to limit the amount of characters in a <textarea>, only the attribute can be used maxlength:

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


Original response:

Its function limitText 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;
}

Besides the events keyup and keydown, it would be nice to hear the keypress also, to make the check 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>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.