Limit characters and display the amount of characters

Asked

Viewed 1,320 times

3

Good guys I got one input for the user to put the name, and below the input I have both typed characters and the maximum amount (0/50).
I wish that every time he typed himself increases the typed characters and when he reaches the limit can no longer type.

And also when deleting a character decrease the typed characters...

2 answers

1


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 by 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

  • I hadn’t seen PHP

  • Blz, do not forget to mark , this is very important for the site.

0

Hello, it’s quite simple to do that

    $(document).ready(function(){   
    $('#iddocampo').keyup(function(){// evento jquery quando o cara digita

        var campo = $("#iddocampo").val();
        var qtde = campo.length;// max characteres
    });
});


You can also use maxlength="50" onkeypress="Return functionJS()"

function funcaoJS(){
     var qtde = document.getElementById("iddocampo").value.length;
}

Browser other questions tagged

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