I am working on a form. The aim is to save the form data to localStorage, and also populate the form fields with the data in the localStorage.
After submitting the form, data do not save to localStorage except I refresh the browser.
Even after I refresh and I see the data in localStorage, I open a new browser, launch the form. I check the localStorage but, the data do not show.
I will appreciate your advice.
Thank you
HTML Code
<form action="https://formspree.io/f/xwkaygyj" method="POST">
<div class="name">
<input id="name" type="text" name="name" required placeholder="Name" oninput="onChangeHandler(this)"/>
<input id="email" type="email" name="email" required placeholder="example@gmail.com" oninput="onChangeHandler(this)"/>
<textarea id="message" name="message" cols="30" rows="7" maxlength="500" placeholder="Write your message here" required oninput="onChangeHandler(this)">
</textarea>
<button type="submit">Send</button>
</div>
</form>
Javascript Code
const formName = document.getElementById('name');
const email = document.getElementById('email');
const message = document.getElementById('message');
let formData = { name: '', email: '', message: '' };
const onChangeHandler = (event) => {
switch (event.name) {
case 'name':
formData = { ...formData, name: event.value };
break;
case 'email':
formData = { ...formData, email: event.value };
break;
case 'message':
formData = { ...formData, message: event.value };
break;
default:
break;
}
localStorage.setItem('data', JSON.stringify(formData));
};
const reloadBrowser = JSON.parse(localStorage.getItem('data'));
if (reloadBrowser) {
formName.value = reloadBrowser.name;
email.value = reloadBrowser.email;
message.value = reloadBrowser.message;
}
I believe you can use AJAX to efficiently submit your request to server, this is cleaner and less error-prone rather than manually capturing input data through swtich statement, furthermore you ascertain the data is successfully submitted to server and a copy is stored in local storage as well.
$.ajax({
type: 'POST',
url: $("form").attr("action"),
data: $("form").serialize(),
//Or your custom data
success: function(response) {
localStorage.setItem('data', JSON.stringify(formData));
},
});