'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>
Solution 1:[1]
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)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
