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’.
2
Answers
I did an example of similar code in action:
I believe the issue lies in your form or another function not properly updating the value in local storage. As demonstrated in the example, please attempt to invoke a function that will update the input value accordingly.
Let’s read what your code is doing out loud.
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.
or you want to get the value when the user inputs the text or changes it.