0

complete noob currently trying to complete a Uni assignment. We are creating a web app using HTML, css and JQuery. I've searched the web for an answer but can't quite figure out what I'm supposed to do.

I have set up a page where users can type in details for a shift, when they submit it, the data is pushed onto an array stored in localStorage using JSON stringify. That part works great and here it is:

var shift = {'location':$('#shift_location').val(), 'start_time':$('#shift_start_time').val(), 'end_time':$('#shift_end_time').val()};
var shift_list = JSON.parse(localStorage.shift);
shift_list.push(shift);
localStorage.shift = JSON.stringify(shift_list);

However I then need to take the last 'shift_location' 'shift_start_time' and 'shift_end_time' that has been added and stick it in a div on the page. This is what I have come up with so far:

var result = JSON.parse(localStorage.shift);
$.each(result, function(k, v) {
  $('.current_shift').text(k + ":" + v);
}); 

However, all that appears on the page is: 0:[object Object].

Any ideas on how to sort this out would be great. Like I said I'm a complete noob and this is my first time posting on here so apologies in advance if I've missed out any important bits of code or framed the question incorrectly.

Thanks James

1
  • [object Object] is stringified. Try console.log and see what it outputs. Commented Jan 10, 2014 at 15:37

2 Answers 2

3

You have an array of objects, you have to get the last object in the array first :

var result = JSON.parse(localStorage.getItem('shift'));

var obj = result.pop();

$('.current_shift').text(obj.start_time + ":" + obj.end_time);
Sign up to request clarification or add additional context in comments.

Comments

1

This is an Array shift_list.

So it looks like locationStorage.shift is an array. That is why the k is an integer. Try this:

$.each(result, function(k, v) {
  $('.current_shift').text(v.location);
}); 

You will see that it is an object since your shift is stored in Objects. For debugging you can do this:

$.each(result, function(k, v) {
  console.log(v);
  $('.current_shift').text(v.location);
}); 

Open Chrome, and look at the console, there you will see your objects.

1 Comment

Thanks, this was really informative I would vote up but cannot as I don't have enough reputation yet!

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.