remaining characters textarea

3

I am writing this code which is to count the amount of characters remaining in a textarea. At first it seemed very simple and has enough documentation on the internet. But I realized that when I copy and paste some text into the textarea, the total remaining characters are positive, meaning I can still type. But this is not the case. Besides not allowing to enter more characters, even I deleting some of the characters with the backspace I can not type anymore. For example, if the text ends in "ball" I can not type "ball" and if I delete it for "bol" (by removing the "a") I can no longer write "ball".

To be clear, the code below works under normal conditions of temperature and pressure, but when a "paste" occurs it gets anomalous behavior, which is to display the remaining number of characters, for example 200, and does not allow more insertion of data. Here is the code I did:

    $("#textAreaComplemento").bind("keyup change", function (e) {
        calculaCaracteresRestantes();
    });

    function calculaCaracteresRestantes() {
        if ($('#textAreaComplemento').val() == undefined) { return false; }

        var text_length = $('#textAreaComplemento').val().length;
        var text_remaining = text_max - text_length;
        $('#textarea_feedback').html(text_remaining);

        return true;
    }

Any suggestion of what may be will be welcome.

EDIT : To reproduce, just copy the code that is in the html comment of this fiddle link . Paste the code as far as you can into the textarea and then try typing.

    
asked by anonymous 04.02.2015 / 22:41

2 answers

1

You could simply use the maxlength property that already makes this limit for you.

var textarea=document.getElementById("textarea");
var caracteresRestantes=document.getElementById("caracteresRestantes");
textarea.oninput=function(e){
    caracteresRestantes.innerHTML=(100-this.value.length);
}
<textarea maxlength="100" id="textarea"></textarea>
<div id="caracteresRestantes">100</div>
    
04.02.2015 / 23:22
1

I answered a similar question here:

link

It seems that when using a texarea with the maxlength attribute set there is an error in the count of characters. Who is preventing you from entering more characters is texarea itself, based on the maxlength you entered in the

<textarea maxlength="200">

In this Fiddle I show you a way to implement the desired behavior: link

By using the "input" event that will also be triggered when text is pasted into textarea.

    
29.10.2015 / 17:03