Search code examples
javascriptformsdomdom-eventslocal-storage

I can't catch the value of my input when I load window using JavaScript DOM


I have to save the data from a form in locaStorage when I load the window. The problem is that when I use the "load" event, I cant catch the value of the input, gives me null. And if I change the "window load" event to the "click" event the button in the form, works fine.

HTML

<form id="contact-form" action="https://formspree.io/f/xbjenldv" method="POST">
     <input id="name" class="input-form" name="name"  type="text" required>
     <button id="submit" type="submit">Get in touch</button>
 </form>

JS

window.onload = () => {
 const name = document.querySelector('#name').value;
 localStorage.setItem('formInfo', JSON.stringify(name));
 const showInfo = JSON.parse(localStorage.getItem('formInfo'));
 console.log(showInfo);
 };

I write 'Bianca' in the input, and when I load the windowname is empty. I need that name value be 'Bianca'.


Solution

  • Let's read what your code is doing out loud.

    1. Onload we run this code
    2. We read the value of the input which is a value at that moment in time and will not update.
    3. We store the value (which is an empty string) into local storage.
    4. We read localstorage and parse it as JSON. So we get our empty string back out.
    5. we display the empty string.

    No where in your code do you read the text that the user enters after the inputed it. The value is just the initial starting value. The variable does not magically update with the new value.

    You want to get the value when the user submits the form.

    <form id="contact-form" action="https://formspree.io/f/xbjenldv" method="POST">
      <input id="name" class="input-form" name="name"  type="text" required>
      <button id="submit" type="submit">Get in touch</button>
    </form>
    
    window.addEventListener("load", () => {
      const form = document.querySelector("#contact-form");
    
      form.addEventListener("submit", () => {
        const name = document.querySelector('#name').value;
        localStorage.setItem('formInfo', JSON.stringify(name));
      });
     
      const showInfo = JSON.parse(localStorage.getItem('formInfo'));
      console.log(showInfo);
    });
    

    or you want to get the value when the user inputs the text or changes it.

      const input = document.querySelector("#name");
    
      input.addEventListener("input", () => {
        const name = input.value;
        localStorage.setItem('formInfo', JSON.stringify(name));
      });