Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
59
rated 0 times [  65] [ 6]  / answers: 1 / hits: 19031  / 11 Years ago, wed, november 13, 2013, 12:00:00

Is there a way to Save from into localstorage
and reuse it again, like this logic:



form ::::::::::::saveINTO:::::::::::::::> localstorage



form <::::::::::::getFROM::::::::::::::: localstorage



after filling the form with data , I want to save the form with its contents in the localstorage, then when i want to fill other from with stored data.



<form>
First name: <input type=text name=firstname><br>
Last name: <input type=text name=lastname>
<button onclick=StoreData();>store into local storage</button>
</form>
<button onclick=RenderForm();>render from data again </button>
<form id=Copyform><form>


JSFIDDLE
please JSFIDDLE answer.



UPDATED


More From » jquery

 Answers
10

You can do that easily, but if you want to store an array you will need to serialize or encode it first because localStorage doesn't deal with arrays. e.g.:



var yourObject = $('#your-form').serializeObject();



To save you do either:



localStorage['variablename'] = JSON.stringify(yourObject) or localStorage.setItem('testObject', JSON.stringify(yourObject));



and to retrieve: JSON.parse(localStorage['yourObject']); or JSON.parse(localStorage.getItem('yourObject')); and then the field values are available as yourObject.fieldName;



EDIT: In the example above I used serializeObject which is a jQuery plugin. The code used is below. (You can use serializeArray if you prefer but you will have to do more work to make your data usable once retrieved):



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;
};

[#74314] Monday, November 11, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
bryonk

Total Points: 161
Total Questions: 116
Total Answers: 107

Location: Albania
Member since Sun, Nov 22, 2020
4 Years ago
bryonk questions
;