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

256
Visualizações
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 Respostas
Responde à pergunta

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