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

250
Views
When using the back button, updated values remain in input field, but code in windows.onload uses default html value

I have an input box with a default value from html. Using the window.onload function I add an event listener to output the value in the box to console log, and I also call the said event in the window.onload function.

As expected when I open the page, it runs the code once and outputs the input default value. And I can edit the value, click the button, and the updated value is also logged to console.

But, if I follow a link to a different page and then use the back button to my original page, the updated text remains in the input box, but the console log outputs the default html value. Clicking the button again myself outputs the updated value as displayed in the input.

How can I make it that when I go back, the updated value that is displayed in the input box is also logged to console, (so that when going back it runs the same code where I left off)?

// Otherwise ran by window.onload = () => {...}
const text = document.getElementById('text');
const button = document.getElementById('button');
button.addEventListener('click', () => console.log(text.value));
button.click();
<input id="text" value="text" />
<input id="button" type="button" value="Click" /><br>
<a href="https://stackoverflow.com/">https://stackoverflow.com/</a>
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

I am not entirely sure, but I think the values are prefilled by the browser immediately after fully loading the DOM synchronously. You can wait for it to finish by calling your code inside setTimeout 0.

setTimeout(function () {
  const text = document.getElementById('text');
  const button = document.getElementById('button');
  button.addEventListener('click', () => console.log(text.value));
  button.click();
}, 0)
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!