Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

184
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda