Search code examples
javascriptjqueryhtmllocal-storageonload

How do I store multiple prepended dates to localStorage?


I am trying to store the current time and date in a table. Currently, on a page load, my code changes the date to reflect the current time.

My code looks like this:

function currentDate() {
  var d = new Date();
  return d.toString();
}
window.onload = function() {
   localStorage.setItem("date", currentDate());
   $('#current-location').prepend('<tr<td>'+localStorage.getItem("date")+'</td>');
}

I tried console.log(localStorage), so I know that one date is being saved there. However, I want to store the date when the page is reloaded (like load the page a second time and 2 dates appear, etc) Do I need an array for this? If so, how would I add array contents to a table?


Solution

  • Yes, you could use an array for that, and just keep pushing dates to the array, like this

    function currentDate() {
      var d = new Date();
      return d.toString();
    }
    
    var arr = JSON.parse(localStorage.getItem("date") || "[]");
    
    arr.push(currentDate())
    
    localStorage.setItem("date", JSON.stringify(arr));
    
    arr.forEach(function(item) {
      $('#current-location').prepend('<tr><td>' + item + '</td></tr>');
    });
    

    FIDDLE