Counter of characters typed in a textarea

5

I have this text box to be validated, should I enter the amount of remaining characters and display these remaining characters in the span, could they help me?

<div class="novaLinha">
  <div>
    <label for="txtVoce">Faleme sobre você:</label>
  </div>
  <div>
    <textarea id="txtVoce" name="txtVoce" cols="40" rows="10"></textarea>
    <p><span id="carResTxtVoce" style="font-weight: bold;">400</span> caracteres restantes</p>
    <p class="aviso" id="avisoTxtVoce" style="display:none;">Este campo não pode ficar vazio!</p>
  </div>
</div>
    
asked by anonymous 13.02.2016 / 21:03

1 answer

2

You can do it like this:

var textarea = document.querySelector('textarea');
var info = document.getElementById('carResTxtVoce');
var limite = 400;
textarea.addEventListener('keyup', verificar);

function verificar(e) {
    var qtdcaracteres = this.value.length;
    var restantes = limite - qtdcaracteres;
    if (restantes < 1) {
        this.value = this.value.slice(0, limite);
        return info.innerHTML = 0;
    }
    info.innerHTML = restantes;
}

In this way you will inform the number of characters missing and when they exceed the limit, cut the excess.

Example: link

You can also, like the @Gabriel Rodrigues suggested you can add in the HTML of the textarea the attribute maxlength="400" is better, and in this case it is simpler and can be just like this:

function verificar(e) {
    var qtdcaracteres = this.value.length;
    var restantes = limite - qtdcaracteres;
    info.innerHTML = restantes;
}
    
13.02.2016 / 21:09