Add character in a <input>

Asked

Viewed 376 times

2

The person types her height (which always has three digits). I want you to autocomplete, example:-

The person type-200

And the software convert to- 2.00

  • 1

    When do you want me to convert? as you type, after x milliseconds without pressing a key or when the input loses focus?

  • Actually you want to make a mask.

1 answer

2


If it always has 3 digits, then limit the input with the attribute maxlength which specifies the maximum number of characters the user can enter.

<input class="number" maxlength="3">

Javascript

Does not allow entering different number values and after typing the third number, inserts the comma automatically after the first number typed.

var el = document.querySelector('input.number');
el.addEventListener('keyup', function (event) {
  if (event.which >= 37 && event.which <= 40) return;

  this.value = this.value.replace(/\D/g, '').replace(/\B(?=(\d{2})+(?!\d))/g, ',');
});
<input class="number" maxlength=3>

  • Better than that, only 2 of it :p

Browser other questions tagged

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