Reputation: 89
I am trying to cache my form data so that in case user loses an internet connection and they comes back and can recover the information through the local storage upon refreshing the page.
I have a large form which has dropdowns, textboxs and checkboxs.
I created a localstorage in which I am storing the entire form in JSON format.
function CacheData()
{
var yourObject = $('#application-form').serializeObject();
localStorage.setItem('testObject', JSON.stringify(yourObject));
}
jQuery.fn.serializeObject = function () {
var formData = {};
var formArray = this.serializeArray();
for (var i = 0, n = formArray.length; i < n; ++i)
formData[formArray[i].name] = formArray[i].value;
return formData;
};
But now, upon refreshing the page, I want to show the data stored in local storage to automatically be filled in the fields.
var myData = JSON.parse(localStorage.getItem("testObject"));
if (myData != null) {
document.getElementById("application-form").innerHTML = myData;
}
with this I just get Object object written and all my fields are gone. How can I desrialize the Json object to put it back in form.Do I need to do for all individual objects or is there a generic function.
I checked Populate HTML form with data saved on Local Storage but its not working for me. The way I want it.
Upvotes: 1
Views: 875
Reputation: 1113
Try using
var myData = JSON.parse(localStorage.getItem("testObject"));
if (myData != null) {
document.getElementById("application-form").innerHTML = JSON.stringify(myData);
}
And than edit your function like this:
document.getElementById("application-form").innerHTML = myData.YourFieldName
Upvotes: 1