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

195
Views
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 answers
Answer question

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