Question:
I need to insert leading zeros into an input text
field. This field can be up to 5 characters + a check digit That is, I need JavaScript to fill with zeros on the left according to what the user types, for example:
123451 = 12345-1
12341 = 01234-1
Where
1236 = 00123-6
Answer:
You can make a function to correct the value of this input. Something like:
function pad(str, length) { const resto = length - String(str).length; return '0'.repeat(resto > 0 ? resto : '0') + str; } // exemplo de testes var testes = [1, 10, 100, 1000]; testes.forEach((teste) => { var resultado = pad(teste, 3); console.log(resultado); });
Adapted to your case it would look like this:
function ajustarInput(str) {
var adicionar = 6 - str.length;
for (var i = 0; i < adicionar; i++) str = '0' + str;
return str.slice(0, 5) + '-' + str.slice(-1);
}
document.getElementById('teste').addEventListener('click', function() {
var input = document.getElementById('input');
input.value = ajustarInput(input.value);
});
<input type="text" id="input" />
<button id="teste">Corrigir</button>
This function reads how many characters are missing from the string, and adds zeros to it. It then separates the last character and inserts a -
before returning the new string.