0

I am using local storage to save an object. I am having troubles than using this object to populate a table. Right now the object is showing up as an array in the third column. How can I use the json array to fill column 1, column 2 and column 3 with the value, key and image from the object.

$(document).on('click', '[data-toggle=add]', function() {
    var latlng = $(this).data('latlng');
    var address = $(this).data('address');
    var image = $(this).data('image');
    var key = $(this).data('id');
    var testObject = {
      'latlng' : latlng,
      'address' : address,
      'image' : image
    };
    localStorage.setItem(key, JSON.stringify(testObject));
    updateTable();
});

function updateTable() {
    var tbody = document.getElementById("output");
    while(tbody.getElementsByTagName("tr").length > 0) {
       tbody.deleteRow(0);
    }
    var row;
    if(localStorage.length == 0) {
       row = tbody.insertRow(i);
       cell = row.insertCell(0);
       cell.colSpan = "4";
       cell.innerHTML = "Nothing to Show";
    }
    for(var i = 0; i < localStorage.length; ++i) {
        row = tbody.insertRow(i);
        cell = row.insertCell(0);
        cell.innerHTML = i;
        cell = row.insertCell(1);
        cell.innerHTML = localStorage.key(i)
        cell = row.insertCell(2);
        cell.innerHTML = localStorage.getItem(localStorage.key(i));
        cell = row.insertCell(3);
        cell.innerHTML = '<button class="btn btn-danger btn-sm" onclick="deleteItem(\'' + localStorage.key(i) + '\');"><i class="fa fa-trash-o"></i> Delete</button>';
    }
}
2
  • can you post a JSFiddle with your HTML as well? Commented Feb 4, 2014 at 18:40
  • jsfiddle.net/ZuGh5 Commented Feb 4, 2014 at 18:46

1 Answer 1

1

You haven't posted all your markup but I believe this is your problem:

You are not retreiving the localStorage correctly. You are saving a stringified version of a JSON object and then you are trying to access it directly as an object. Instead, you need to retrieve the localstorage item and parse it back to a JSON object, then iterate through it or access its properties as an object.

Replace:

cell.innerHTML = localStorage.key(i);

With:

json = JSON.parse(localStorage.key(i));

cell.innerHTML = json.latlng;// or json.address or json.image;

Hope this helps!

Sign up to request clarification or add additional context in comments.

1 Comment

Awesome. I had tried to parse the json about 15 different ways. Was always forgetting the .key(i) so I kept getting undefined. Thanks very much

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.