javascript – remaining characters textarea

Question:

I'm writing this code that is to count the amount of characters left in a textarea. At first it seemed very simple and there is a lot of documentation on the internet. But I noticed that when I copy and paste some text into the textarea, the total number of characters left is positive, that is, I can still type. However, that is not what happens. In addition to not allowing typing more characters, even if I erased some of the characters with the backspace I can't type anymore. For example, if the text ends in "bola" I can't write "bolar" and if I erase it to just "bol" (removing the "a") I can't write "bolar" anymore.

To be clear, the code below works under normal conditions of temperature and pressure, but when there is a "paste" it has the anomalous behavior, which is to display the amount of characters left, for example 200, and does not allow further data entry . Here's the code I made:

    $("#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 it might be would be welcome.

EDIT : To reproduce, just copy the code that is in the html comment of this fiddle http://jsfiddle.net/sLr8co1n/4/ . Paste the code as much as you can into the textarea and then try typing.

Answer:

You could just use the maxlength property which already sets 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>
Scroll to Top
AllEscort