Validation remaining characters

Asked

Viewed 42 times

-2

Crie a função JavaScript chamada “contaCaracteresRestantes(idCampoTexto, idSpan)” que conte quantos caracteres restam no campo “txtVoce” e mostre esta quantidade de caracteres restantes no span“carResTxtVoce”. The field in the HTML code is defined as having 40 columns and 10 rows, that is, 400 characters. Tip: the function must be called in the onChange event of the "txtVoce" field. Tip 2: the input arguments idCampo and idSpan must be the id’s of the "txtVoce" field and the span "carResTxtVoce".

Please, I’ve tried, but I can’t resolve this issue, you can help me?

<div><label for="txtVoce">Faleme sobre você:</label></div>
            <div><textarea id="txtVoce" maxlength="100" name="txtVoce" cols="40" rows="10"></textarea>
            <p><span id="carResTxtVoce" style="font-weight: bold;">400</span> caracteres restantes</p>

1 answer

2

You can do it like this:

function contaCaracteresRestantes(idCampoTexto, idSpan) {
  var n = document.getElementById(idCampoTexto).value.length;
  document.getElementById(idSpan).innerHTML = 400 - n;
}
<div><label for="txtVoce">Faleme sobre você:</label></div>
<div><textarea id="txtVoce" maxlength="100" name="txtVoce" cols="40" rows="10" onKeyUp="contaCaracteresRestantes('txtVoce', 'carResTxtVoce')"></textarea>
<p><span id="carResTxtVoce" style="font-weight: bold;">400</span> caracteres restantes</p>

If you want the counter to update while typing (as in the example above), use onKeyUp and/or onKeyDown instead of onChange, that was suggested in the statement. If use onChange, you will have to click off the textarea for the counter to update.

Browser other questions tagged

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