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'.
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.
<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));
});