javascript – remaining characters textarea


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

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

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

        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 . Paste the code as much as you can into the textarea and then try typing.


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 maxlength="100" id="textarea"></textarea>
<div id="caracteresRestantes">100</div>
Scroll to Top