javascript – Limit characters and display number of characters

Question:

Well guys, I have an input for the user to put the name, and under the input I have the amount of typed characters and the maximum amount (0/50).
I wanted that every time he types himself, the typed characters are increased and when he reaches the limit he can no longer type.

And also when deleting a character, decrease the typed characters…

Answer:

A very practical way is to first put a maxlength="50" in the field to limit the number of characters and the script below to change the counter counting the number of characters typed:

 document.querySelector("input[name='nome']") // seleciona o campo pelo atributo "name" .addEventListener("input", function(){ // evento "input" que detecta mudança de valor no campo var cars = this.value.length; //conta a quantidade de caracteres // se for menor ou igual a 50, altera texto com o valor no span if(cars <= 50) document.querySelector(".limite").textContent = cars; });
 <input type="text" name="nome" maxlength="50"> <span class="limite">0</span>/50
Scroll to Top
AllEscort