Home > Mobile >  How to make an HTML input field not accepting successive identical chars when the key is being press
How to make an HTML input field not accepting successive identical chars when the key is being press

Time:12-20

I have an HTML input field but if the user keeps on pressing a key, it will add the same letter non-stop. I want to suppress this behavior.

How can I override the input component's input event listener to not allow to not add successive characters when the key is being kept pressed down?

CodePudding user response:

<input type="text" oninput="this.value = this.value.replace(/(.)\1 /g, '$1')" />

https://jsfiddle.net/sxwr2u3z/

CodePudding user response:

Another answer. This one uses KeyboardEvent.repeat to detect continuous pressing.

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

input.addEventListener('input', function (event) {
    this.value = this.value.replace(/.$/,'');
});
input.addEventListener('keyup', function (event) {
    if (event.repeat) return;
  this.value  = event.key;
});
  • Related