I have a form where I want to save the data in local storage on keyup.
So if the user comes back to the form the data they have already filled in can be loaded from their localStorage.
I have the below see fiddle which is storing the data in local storage as I want.
But I am having trouble pre populating the form with this data.
I know that closestID is undefined when I try and load it, how can I get the value for each id of Staff so that I can populate my form, or is there a better way?
<form id="myForm">
<div id="div-1" class="staff">
<input type="name" name="name" value="Tim">
<input type="number" name="age" value="18">
</div>
<div id="div-2" class="staff">
<input type="name" name="name" value="Sarah">
<input type="number" name="age" value="32">
</div>
<div id="div-3" class="staff">
<input type="name" name="name" value="Brendan">
<input type="number" name="age" value="48">
</div>
</form>
<script>
jQuery("input").keyup(function () {
var closestID = jQuery(this).closest('[id]').attr('id');
var staffArray = $("#" + closestID + " input").map(function () {
return {
"title": this.name,
"value": this.value
}
}).get();
//set that to localStorage
localStorage["id-" + closestID] = JSON.stringify(staffArray);
});
var getFromStore = function (closestID) {
//check if store values are null, if null, make store =[]
var store = [undefined, null].indexOf(localStorage["id-" + closestID]) != -1 ? [] : JSON.parse(localStorage["id-" + closestID]);
//check if store is empty
if (store.length != 0) {
//loop over store if it aint empty and append the content into myStorage div
for (var k in store) {
var myTitle = store[k]["title"];
var myVal = store[k]["value"];
console.log('myTitle ' + myTitle);
console.log('myVal ' + myVal);
$("#" + closestID + " input[name='" + myTitle + "']").attr( "value", myVal );
}
}
}
getFromStore(closestID);
</script>