Character counter typed in a textarea

Asked

Viewed 1,188 times

6

I have this text box to be validated, should inform the amount of characters remaining and show these characters remaining in span, could 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>

2 answers

3

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;
}

This way you inform the amount of characters missing and when they exceed the limit cut the excess.

Example: https://jsfiddle.net/bsy6m8b7/

You can too, like @Gabriel Rodrigues suggested you can join the attribute in the textarea HTML maxlength="400" it is better, and in this case it becomes simpler and it can only be so:

function verificar(e) {
    var qtdcaracteres = this.value.length;
    var restantes = limite - qtdcaracteres;
    info.innerHTML = restantes;
}
  • 2

    +1, I believe Voce should add a maxlength="400"in the textarea to avoid typing more characters and cutting them, it is more natural.

  • 1

    @Gabrielrodrigues thank you. Regarding your suggestion this is already there. On the line this.value = this.value.slice(0, limite);

  • 2

    html maxlength intercepts faster than javascript keyup, so when it is going to type the 400 character the letter will not appear and then it will be cut.

  • 2

    @Gabrielrodrigues thought you were suggesting via Javascript. In HTML is much better than via Javascript. I added this in the reply, thank you.

  • 1

    da para deixar mais xuto assim:https://jsfiddle.net/bsy6m8b7/1/

  • @Exact Gabrielrodrigues, if the limit is set in HTML is fine.

Show 1 more comment

1

https://docs.angularjs.org/api/ng/directive/ngKeyup

<p>Typing in the input box below updates the key count</p>
<input ng-keyup="count = count + 1" ng-init="count=0"> key up count: {{count}}

<p>Typing in the input box below updates the keycode</p>
<input ng-keyup="event=$event">
<p>event keyCode: {{ event.keyCode }}</p>
<p>event altKey: {{ event.altKey }}</p>

Browser other questions tagged

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