search history with localStorage variable in HTML


I'm creating an jQuery mobile app with PhoneGap and I want to list old search results (entered by a form and stored in localStorage).

There are two different problems to solve:

1) I would store a result in a localStorage array and if the user is searching a second time, the result should be added to the array after the old result like: city[0] = "New York", city[1] = "Paris" ... how can I save and read a string in an array, like:

localStorage.setItem('city[i]', $('#city').val()); 
or
localStorage.getItem('city[i]');

2) Now I want to show the search history. I've tried this, but:

  • I don't know how to display the localStorage array or variable in a html list and ...
  • if no variable in localStorage, the website doesn't load.

<div id="lastResults"></div>

<script>
    var history = "";
    if (localStorage.getItem("history") !== "") {
        var history = localStorage.getItem("history");
    }

    if ( history !== "") {
        $("#lastResults").html(
            "<b>Last Results:</b>" +
            "<ul data-role=\"listview\" data-inset=\"true\" >" +
                "<li><a href=\"#test\"> " + document.write(history) + " </a></li>" +
            "</ul>"
        );
    }
</script>
<div id="lastResults"></div>

<script type="text/javascript">
   //To Check and show previous results in **lastResults** div
   if (localStorage.getItem("history") != null)
   {
       var historyTmp = localStorage.getItem("history");
       var oldhistoryarray = historyTmp.split('|');
       $('#lastResults').empty();
       for(var i =0; i<oldhistoryarray.length; i++)
       {
           $('#lastResults').append('<p>'+oldhistoryarray[i]+'</p>');
       }
   }

   //Storing New result in previous History localstorage
   if (localStorage.getItem("history") != null) 
   {
       var historyTmp = localStorage.getItem("history");
       historyTmp += '|Paris|Pakistan|China|US';
       localStorage.setItem("history",historyTmp);
   }
   else
   {
       var historyTmp = 'Paris|Pakistan|China|US';
       localStorage.setItem("history",historyTmp);
   }
</script>

Note I have used jquery for code shortening.


LocalStorage stores key value pairs where both the key and the value are strings. One way to get around this is to use a JSON object to store your data and use JSON.stringify and JSON.parse to change the data from object to string and back.

EXAMPLE:

var historyObj = { city: [] };

function onLoad() {
  if(localStorage.getItem('history') != '') {
    historyObj = JSON.parse(localStorage.getItem('history'));
  }
}

function addHistory(dataToSave) {
  historyObj.city.push(dataToSave);
  localStorage.setItem('history',JSON.stringify(historyObj));
}