2

I have a html input that has a fixed length of 7. If the users types 1234, how can I prefix this input with a number of zeros in order to have the required length of 7?

I want to do this only in the UI because I already have a method in ts code for prefixing with zeros this input in order to send this correctly to backend.

 <input formControlName="userNumber" type="text" class="form-control" placeholder="User #" aria-label="userNumber" aria-describedby="userNumber">
Saugat Bhattarai
  • 2,614
  • 4
  • 24
  • 33
user2004
  • 1,783
  • 4
  • 15
  • 42
  • Does this answer your question? [Fill html input with zeros (0)](https://stackoverflow.com/questions/33124806/fill-html-input-with-zeros-0) – Roy Bogado Apr 22 '20 at 10:12

1 Answers1

3

You can make use of input event on input field. Once user enters some numbers and then when the input field loses focus, required number of zeroes will be added.

const $input = document.querySelector('input');

$input.addEventListener('change', (e) => {
  const value = e.target.value;
  const length = e.target.value.length;
  
  if (length === 0) {
     $input.value = value;
  }
  else if (length < 7) {
    $input.value = '0'.repeat(7-length) + value;
  }
});
<input formControlName="userNumber" type="text" class="form-control" placeholder="User #" aria-label="userNumber" aria-describedby="userNumber">
Yousaf
  • 27,861
  • 6
  • 44
  • 69