Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

js onkeypress not working until next input

I am trying to insert a hyphen when the input size is exactly two.
Here is my code

document.getElementById('numberInput').onkeypress = function() {
  if (this.value.length == 2) {
    this.value = this.value + '-';
  }
}
<input type="text" id="numberInput">

But the problem is the – doesn’t appears until third character is inputted. Although the hyphen is placed properly, i mean after two characters.

How can i get hyphen right after entering two characters?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I tried onkeyup but the problem is it also fires when i press backspace button. When there are two characters, the hyphen appears but at that point if I press backspace and delete the hyphen it immediately comes back. So i choose onkeypress

>Solution :

the value of the input text box, during onKeyPress is always the value before the change. This allows the event listener to cancel the keypress.

To get the value after the field value has been updated, schedule a function to run on the next event loop. The usual way to do this is to call setTimeout with a timeout of 0:

document.getElementById('numberInput').onkeypress = function() {
  // arrow function keeps scope
  setTimeout(() => {
    // now it is the value after the keypress
    if (this.value.length == 2) {
      this.value = this.value + '-';
    }
  }, 0);
}
<input type="text" id="numberInput">
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading