Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

197
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda