Reputation: 143
I am successfully creating a jquery object then saving the object as a json string into a local storage variable using the following code which loops through a list and adds the items to the myObject variable and then saves the object to a local storage variable.
var x =$("[name=checklist]").length;
var myObject = {};
myObject.Vehicle_Check = [x];
$("[name=checklist]").each(function(index){
if (index >0) {
myObject.Vehicle_Check.push({});
var PT = $("[name=problemtxt_" + index + "]").val(); //the fault label
var CL = $("[name=checklbl_" + index + "]").text(); //the question
var d = $("[name=optiongroup_" + index + "]:checked").val();
if (d == 'Item 1') {
d='OK'
}
else if (d == 'Item 2') {
d='Fault'
localStorage.setItem('fault', 1);
}
myObject.Vehicle_Check[index].question = CL;
myObject.Vehicle_Check[index].result = d;
myObject.Vehicle_Check[index].Fault = PT;
}
});
localStorage.setItem('results' ,JSON.stringify(myObject));
I have tried to do the same by constructing the object one item at a time saving it to a local storage variable then when I wish to add another item retrieving the object back from the variable using parseJSON and adding an additional item then saving back to the variable. I have not got this working correctly. How should I construct this properly?
Initiate the object:
var myObject = {};
myObject.Vehicle_Check = [18];
myObject.Vehicle_Check.push({});
localStorage.setItem('checkobject',JSON.stringify(myObject));
Add to the object:
var myObject = jQuery.parseJSON(localStorage.getItem('checkobject'));
myObject.Vehicle_Check.push({});
myObject.Vehicle_Check[I].question = 'First test!';
myObject.Vehicle_Check[I].result = 'OK';
myObject.Vehicle_Check[I].Fault = 'none';
localStorage.setItem('checkobject',JSON.stringify(myObject))
Upvotes: 1
Views: 166
Reputation: 27012
You haven't defined I
. You might do something like this instead so you don't have to worry about the index:
var myObject = {};
myObject.Vehicle_Check = [];
localStorage.setItem('checkobject', JSON.stringify(myObject));
...
var myObject = jQuery.parseJSON(localStorage.getItem('checkobject'));
var next = {
question: 'First test!',
result: 'OK',
Fault: 'none'
};
myObject.Vehicle_Check.push(next);
localStorage.setItem('checkobject', JSON.stringify(myObject));
Edit - This could simplify things even further, depending on your usage:
myObject.Vehicle_Check.push({
question: 'First test!',
result: 'OK',
Fault: 'none'
});
Upvotes: 1