Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

183
Views
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?

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

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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">

about 4 years ago · Juan Pablo Isaza Report

0

Why not hook onto the input event instead?

document.getElementById("numberInput")
  .addEventListener("input", function(e) {
    if (e.target.length === 2) {
      e.target.value += "-";
    }
  });
about 4 years ago · Juan Pablo Isaza Report

0

This is happening because of event loop. this.value is updated only after key press. So in this case you always end up with old state. I would recommend using other listener method, in this case oninput. And retrieving latest input value throughout function parameters

In your case fix would be:

document.getElementById('numberInput').oninput = function (event) {
  if (event.target.value.length === 2) {
    this.value = event.target.value + '-'
  }
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!