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

196
Visualizações
HTML Input - Undo history lost when setting input value programmatically

I have an HTML input. When a user types in it, I've set up the 'input' event to handle updating the input to a filtered version of what the user typed (as well as updating selectionStart and selectionEnd for smooth UX). This happens constantly in order to give the proper effect.

What I've noticed, however, is that whenever JS sets the value of an input via input.value = '...';, it appears the undo history for the input disappears. That is, pressing Ctrl-Z with it focused no longer steps back to the previous state.

Is there any way to either provide the input custom undo history, or otherwise prevent it from losing the history whilst still changing its value?


Here is a minimal example of my issue:
After typing in the top input (which rudimentarily adds periods between every character), Ctrl-Z does not undo.

<body>
    <input type="text" id="textbox" placeholder="No undo"/><br/>
    <input type="text" id="textbox2" placeholder="Undo"/>
    <script>
        var tbx = document.getElementById("textbox");
        tbx.addEventListener('input', () => {
            tbx.value = tbx.value + '.'
        });
    </script>
</body>

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You can try storing the input's previous value in a variable, then listen for the Ctrl + Z key combination in a keydown event listener attached to the input. When it is fired, you can set the value of the input to the previous stored value.

btn.addEventListener('click', function(){
  savePrevInput(input.value)
  input.value = "Hello World!";
})

var prevInput;

function savePrevInput(input){
  prevInput = input;
}

input.addEventListener("keydown", function(e){
  if(e.ctrlKey && e.keyCode == 90){
    input.value = prevInput;
    input.selectionStart = prevInput.length;
  }
})
<input id="input"/>

<button id="btn">Change</button>

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