HTML5 localStorage Value Array Error

  • (2 Pages)
  • +
  • 1
  • 2

22 Replies - 4111 Views - Last Post: 11 April 2013 - 12:37 PM

#1 Liam O'Byrne  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 41
  • Joined: 02-April 13

HTML5 localStorage Value Array Error

Posted 02 April 2013 - 05:16 PM

I have been tirelessly attempting to store multiple values within particular keys using localStorage, however, I have been unsuccessful.

I have successfully managed to store only 1 value per key. Anytime I try to add more values to a key, it overwrites the existing value. I tried using the .push method, but this didn't work for me. So far, I am able to produce the following:

EXAMPLE
"You travelled 24 miles in on 03 April 2013 00:39:17."

Below is my Javascript:

distance = new Array();
timestamp = new Array();

localStorage.setItem("distance", distance);
localStorage.setItem("timestamp", timestamp);


// localStorage
if (typeof (Storage) !== "undefined") {
    if (localStorage.getItem("distance") === null || localStorage.getItem("timestamp") === null) {
        document.getElementById("history").innerHTML = "There are currently no records to display.";
    } else {
        document.getElementById("history").innerHTML = "<br>You travelled " + localStorage.getItem("distance") + " miles in " + "on " + localStorage.getItem("timestamp") + ".";
    }
} else {
    document.getElementById("history").innerHTML = "Your browser does not support the localStorage API.";
}


AIM
My aim is to produce a list of records. For example:

"You travelled 24 miles in on 03 April 2013 00:39:17."
"You travelled 16 miles in on 22 January 2012 16:52:44."
and so on...

Any help or assistance would be greatly appreciated.

Is This A Good Question/Topic? 0
  • +

Replies To: HTML5 localStorage Value Array Error

#2 Takk  Icon User is offline

  • D.I.C Head

Reputation: 40
  • View blog
  • Posts: 111
  • Joined: 08-March 13

Re: HTML5 localStorage Value Array Error

Posted 02 April 2013 - 05:29 PM

localstorage is string only, you can delimit strings, but no array support as of now.
Was This Post Helpful? 0
  • +
  • -

#3 Atli  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 3717
  • View blog
  • Posts: 5,979
  • Joined: 08-June 10

Re: HTML5 localStorage Value Array Error

Posted 02 April 2013 - 05:40 PM

Hey.

Values stored in the localStorage or sessionStorage are always strings. If you try to store a normal object or array, you will just get the [object Object] or [object Array] strings like you would if you tried to print them.

To store an array in those storage mechanisms, you need to manually convert them to and from a serialized form. The obvious format for Javascript is of course JSON, and that is what you should use.

This is how I would imagine the code you are trying to create could look like:

/**
 * Add a distance to the distances object in the localStorage.
 *
 * @param {Number} distance The distance to store.
 */
function addDistance(var distance) {
	// Fetch the "distances" object from the localStorage and
	// either unserialize it using JSON.parse, or create a new
	// array if the localStorage has no distances object.
	var distances = localStorage.getItem("distances");
	if (!distances) {
		distances = [];
	}
	else {
		distances = JSON.parse(distances);
	}
	
	// Add the new distance to the distances array as a
	// new object, containing the distance and the current
	// timestamp.
	distances.push({
		distance: distance,
		timestamp: (new Date()).getTime()
	});
	
	// Serialize the new distances object using JSON.stringify
	// and overwrite the old distances string in the localStorage.
	localStorage.setItem("distances", JSON.stringify(distances));
}


Note there that the distance and the timestamp are stored together in an object in a single array element, rather than being stored separately in two different arrays. This is far easier to maintain reliably, as you don't have to worry about the two arrays going out of sync.
Was This Post Helpful? 0
  • +
  • -

#4 JMRKER  Icon User is offline

  • D.I.C Addict

Reputation: 128
  • View blog
  • Posts: 826
  • Joined: 25-October 08

Re: HTML5 localStorage Value Array Error

Posted 03 April 2013 - 09:01 AM

Question about implementation: :helpsmilie:/>

How much of post #1 is retained if post #3 in incorporated into the script?

Does the HTML portion consist of?
1. An input textbox of the distance (id="distance")
2. A button to save the information.
3. A <div> or <pre> element to display the created or stored results.
4. A button to display the stored results
Was This Post Helpful? 0
  • +
  • -

#5 Liam O'Byrne  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 41
  • Joined: 02-April 13

Re: HTML5 localStorage Value Array Error

Posted 03 April 2013 - 11:51 AM

Hi!

Here is a link to jsfiddle [link]http://jsfiddle.net/ePASe/2[/link]/.

Atli's solution did not work! It still continues to overwrite existing values in localStorage.
Was This Post Helpful? 0
  • +
  • -

#6 JMRKER  Icon User is offline

  • D.I.C Addict

Reputation: 128
  • View blog
  • Posts: 826
  • Joined: 25-October 08

Re: HTML5 localStorage Value Array Error

Posted 03 April 2013 - 12:27 PM

I played with it and came up with this solution.
I have not yet looked at yours.
<!DOCTYPE HTML>
<html>
<head>
<title> Local Storage Arrays </title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

<style type="text/css">
 #clrButton { display:none; }
</style>

</head>
<body>
<input type="text" id="distance">
 <button onclick="addDistance($_('distance').value)"> Save </button>
 <button onclick="showDistances()">Show</button>
 <input type="checkbox" id="clrCBox" onclick="clrCheck()">
 <button id="clrButton" onclick="clearDistances()">Clear</button><br>
<pre id="history"></pre>

<script type="text/javascript">
// Modified from:
//   http://www.dreamincode.net/forums/topic/317492-html5-localstorage-value-array-error/
/* Add a distance to the distances object in the localStorage.
 *
 * @param {Number} distance The distance to store.
 */
function addDistance(distance) {
// Fetch the "distances" object from the localStorage and
// either unserialize it using JSON.parse, or create a new
// array if the localStorage has no distances object.
  var distances = localStorage.getItem("distances");
  if (!distances) { distances = []; }
             else { distances = JSON.parse(distances); }
	
// Add the new distance to the distances array as a
// new object, containing the distance and the current timestamp.
  distances.push({distance: distance, timestamp: (new Date()).getTime()});
	
// Serialize the new distances object using JSON.stringify
// and overwrite the old distances string in the localStorage.
  localStorage.setItem("distances", JSON.stringify(distances));
}
function $_(IDS) { return document.getElementById(IDS); }

function showDistances() {
  var recs = JSON.parse(localStorage.getItem('distances'));
  var str = '';  var ts;
  if (recs != null) {
    for (var i=0; i<recs.length; i++) { 
      str += recs[i]['distance'] + ' --&gt; ';
      ts = new Date(recs[i]['timestamp']);
      str += ts.toDateString() + ' ' + ts.toTimeString() + '<br>';
//      str += ts.toString() + '<br>';
    }
  } else { str = 'Nothing to display yet!'; }
  $_('history').innerHTML = str;  // localStorage.getItem('distances');
}
function clrCheck() {
  if ($_('clrCBox').checked == true) { $_('clrButton').style.display='inline' }
                                else { $_('clrButton').style.display = 'none'; }
}
function clearDistances() {
  if ($_('clrCBox').checked) { localStorage.removeItem("distances"); }
}
</script>
</body>
</html>



PS: Finally got a look at your JSfiddle code ... it did not run for me (???)

This post has been edited by JMRKER: 03 April 2013 - 12:30 PM

Was This Post Helpful? 0
  • +
  • -

#7 andrewsw  Icon User is offline

  • Fire giant boob nipple gun!
  • member icon

Reputation: 3354
  • View blog
  • Posts: 11,353
  • Joined: 12-December 12

Re: HTML5 localStorage Value Array Error

Posted 03 April 2013 - 12:30 PM

View PostLiam O, on 03 April 2013 - 06:51 PM, said:

Hi!

Here is a link to jsfiddle [link]http://jsfiddle.net/ePASe/2[/link]/.

Atli's solution did not work! It still continues to overwrite existing values in localStorage.

This is quite cheeky, if not rude. Atli already suggested that this is how your code could look - he never suggested it would run unaltered. However, despite his statement, it worked for me straight-away.

This post has been edited by andrewsw: 03 April 2013 - 12:31 PM

Was This Post Helpful? 0
  • +
  • -

#8 Liam O'Byrne  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 41
  • Joined: 02-April 13

Re: HTML5 localStorage Value Array Error

Posted 03 April 2013 - 12:59 PM

View PostJMRKER, on 03 April 2013 - 12:27 PM, said:

I played with it and came up with this solution.
I have not yet looked at yours.
<!DOCTYPE HTML>
<html>
<head>
<title> Local Storage Arrays </title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

<style type="text/css">
 #clrButton { display:none; }
</style>

</head>
<body>
<input type="text" id="distance">
 <button onclick="addDistance($_('distance').value)"> Save </button>
 <button onclick="showDistances()">Show</button>
 <input type="checkbox" id="clrCBox" onclick="clrCheck()">
 <button id="clrButton" onclick="clearDistances()">Clear</button><br>
<pre id="history"></pre>

<script type="text/javascript">
// Modified from:
//   http://www.dreamincode.net/forums/topic/317492-html5-localstorage-value-array-error/
/* Add a distance to the distances object in the localStorage.
 *
 * @param {Number} distance The distance to store.
 */
function addDistance(distance) {
// Fetch the "distances" object from the localStorage and
// either unserialize it using JSON.parse, or create a new
// array if the localStorage has no distances object.
  var distances = localStorage.getItem("distances");
  if (!distances) { distances = []; }
             else { distances = JSON.parse(distances); }
	
// Add the new distance to the distances array as a
// new object, containing the distance and the current timestamp.
  distances.push({distance: distance, timestamp: (new Date()).getTime()});
	
// Serialize the new distances object using JSON.stringify
// and overwrite the old distances string in the localStorage.
  localStorage.setItem("distances", JSON.stringify(distances));
}
function $_(IDS) { return document.getElementById(IDS); }

function showDistances() {
  var recs = JSON.parse(localStorage.getItem('distances'));
  var str = '';  var ts;
  if (recs != null) {
    for (var i=0; i<recs.length; i++) { 
      str += recs[i]['distance'] + ' --&gt; ';
      ts = new Date(recs[i]['timestamp']);
      str += ts.toDateString() + ' ' + ts.toTimeString() + '<br>';
//      str += ts.toString() + '<br>';
    }
  } else { str = 'Nothing to display yet!'; }
  $_('history').innerHTML = str;  // localStorage.getItem('distances');
}
function clrCheck() {
  if ($_('clrCBox').checked == true) { $_('clrButton').style.display='inline' }
                                else { $_('clrButton').style.display = 'none'; }
}
function clearDistances() {
  if ($_('clrCBox').checked) { localStorage.removeItem("distances"); }
}
</script>
</body>
</html>



PS: Finally got a look at your JSfiddle code ... it did not run for me (???)



Here is a link to the server: http://liamobyrne.ne...ges/locate.html
Was This Post Helpful? 0
  • +
  • -

#9 andrewsw  Icon User is offline

  • Fire giant boob nipple gun!
  • member icon

Reputation: 3354
  • View blog
  • Posts: 11,353
  • Joined: 12-December 12

Re: HTML5 localStorage Value Array Error

Posted 03 April 2013 - 01:12 PM

Your function clearWatch() refers to a variable named distance, but this is only defined (and available) within your function showPosition().
Was This Post Helpful? 0
  • +
  • -

#10 JMRKER  Icon User is offline

  • D.I.C Addict

Reputation: 128
  • View blog
  • Posts: 826
  • Joined: 25-October 08

Re: HTML5 localStorage Value Array Error

Posted 03 April 2013 - 01:41 PM

View PostLiam O, on 03 April 2013 - 01:59 PM, said:

...

Here is a link to the server: http://liamobyrne.ne...ges/locate.html


Your linked example comments out the "../js/localstorage.js" external file
so it does nothing for me insofar as solving your problem.

I continued to modify the version I was playing with using 'Atli's code.
Few more modifications to make sure I understood what he was doing...
<!DOCTYPE HTML>
<html>
<head>
<title> Local Storage Arrays </title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

<style type="text/css">
 #clrButton { display:none; }
</style>

</head>
<body>
<input type="text" id="distance">
 <button onclick="addDistance($_('distance').value)"> Save </button>
 <button onclick="showDistances()">Show</button>
 <input type="checkbox" id="clrCBox" onclick="clrCheck()">
 <button id="clrButton" onclick="clearDistances()">Clear</button><br>
<pre id="history"></pre>

<script type="text/javascript">
// Modified from:
//   http://www.dreamincode.net/forums/topic/317492-html5-localstorage-value-array-error/
/* Add a distance to the distances object in the localStorage.
 *
 * @param {Number} distance The distance to store.
 */
function addDistance(distance) {
// Fetch the "distances" object from the localStorage and
// either unserialize it using JSON.parse, or create a new
// array if the localStorage has no distances object.
  var distances = localStorage.getItem("distances");
  if (!distances) { distances = []; }
             else { distances = JSON.parse(distances); }
	
// Add the new distance to the distances array as a
// new object, containing the distance and the current timestamp.
  distances.push({distance: distance, timestamp: (new Date()).getTime()});
	
// Serialize the new distances object using JSON.stringify
// and overwrite the old distances string in the localStorage.
  localStorage.setItem("distances", JSON.stringify(distances));
  showDistances();
}

function $_(IDS) { return document.getElementById(IDS); }
function padN(n) { return n = (n < 10) ? '0'+n : n; }
function showDistances() {
  var str = '';
/* */
  var ts;
  var recs = JSON.parse(localStorage.getItem('distances'));  // .reverse();  // alt. display (LIFO)
  if (recs != null) {
    for (var i=0; i<recs.length; i++) { 
      ts = new Date(recs[i]['timestamp']);
      str += (padN(ts.getMonth()+1))+'/'+padN(ts.getDate())+'/'+ts.getFullYear()+' ';
      var hrs = ts.getHours()+1;  var ampm = '';  // 'am';
//      if (hrs > 12) { hrs -= 12; ampm = 'pm'; }
      str += padN(hrs)+':'+padN(ts.getMinutes())+':'+padN(ts.getSeconds())+' '+ampm+' - ';
      str += recs[i]['distance'] + '<br>';
    }
  } else { str = 'Nothing to display yet!'; }
/* */
//  str = localStorage.getItem('distances');  // raw JSON display for testing purposes only

  $_('history').innerHTML = str;  // localStorage.getItem('distances');
}
function clrCheck() {
  if ($_('clrCBox').checked == true) { $_('clrButton').style.display='inline' }
                                else { $_('clrButton').style.display = 'none'; }
}
function clearDistances() {
  if ($_('clrCBox').checked) { localStorage.removeItem("distances"); }
  showDistances();
}
window.onload = function() { showDistances(); }
</script>
</body>
</html>


:bananaman:/>/>

This post has been edited by JMRKER: 03 April 2013 - 01:42 PM

Was This Post Helpful? 1
  • +
  • -

#11 Atli  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 3717
  • View blog
  • Posts: 5,979
  • Joined: 08-June 10

Re: HTML5 localStorage Value Array Error

Posted 03 April 2013 - 09:13 PM

View PostLiam O, on 03 April 2013 - 06:51 PM, said:

Atli's solution did not work! It still continues to overwrite existing values in localStorage.

The code I posted does work, like andrewsw said, but it wasn't meant as a copy-paste snippet. The point of it was to show you how to work with arrays inside of the Storage interfaces so you could then apply that knowledge to your own code.

View Postandrewsw, on 03 April 2013 - 08:12 PM, said:

Your function clearWatch() refers to a variable named distance, but this is only defined (and available) within your function showPosition().

He doesn't prefix it with a "var" in there, though, so it's actually a global. It's still not a good idea to define it like this. If clearWatch is called before showPosition, then it won't be set yet.
Was This Post Helpful? 0
  • +
  • -

#12 Liam O'Byrne  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 41
  • Joined: 02-April 13

Re: HTML5 localStorage Value Array Error

Posted 09 April 2013 - 12:16 PM

3 weeks have gone by and I still can't seem to solve this. I'm beginning to believe it's not at all possible to achieve what I want to achieve.

I appreciate all of the comments and feedback I have received. However, I still can't achieve my goal.

I will specify my aim as clearly as possible to make sure you understand what it is I want.

I have also provided a jsfiddle link (http://jsfiddle.net/9qnBA/) so you can see my problem.

ACHIEVED
When the user clicks 'Start', geolocation starts. Detailed information is also provided below the map.
When the user clicks 'Stop', geolocation stops and localStorage is activated. localStorage is used to get the users distance information and timestamp.

I then display the information in the "History" section of the web page as follows:

"You travelled (whatever miles) in on (timestamp)."

PROBLEM
Every time I run the application and click 'Stop' to add a new record (i.e. distance, timestamp) to localStorage it overwrites the existing (previous) localStorage data.

I have attempted to put both the distance and timestamp into arrays and push new data into the array but it doesn't work.

AIM
My aim is to produce a list of records. Every time the user clicks 'Stop', their data is added to localStorage and outputted in the "History" section of the web page like this:

"You travelled (whatever miles) in on (timestamp)."
"You travelled (whatever miles) in on (timestamp)."
"You travelled (whatever miles) in on (timestamp)."
"You travelled (whatever miles) in on (timestamp)."
"You travelled (whatever miles) in on (timestamp)."

ANY help or recommendation would be gratefully accepted.
Was This Post Helpful? 0
  • +
  • -

#13 Liam O'Byrne  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 41
  • Joined: 02-April 13

Re: HTML5 localStorage Value Array Error

Posted 09 April 2013 - 12:32 PM

3 weeks have gone by and I still can't seem to solve this. I'm beginning to believe it's not at all possible to achieve what I want to achieve.

I appreciate all of the comments and feedback I have received. However, I still can't achieve my goal.

I will specify my aim as clearly as possible to make sure you understand what it is I want.

I have also provided a jsfiddle link (http://jsfiddle.net/9qnBA/) so you can see my problem.

ACHIEVED

When the user clicks 'Start', geolocation starts. Detailed information is also provided below the map.
When the user clicks 'Stop', geolocation stops and localStorage is activated. localStorage is used to get the users distance information and timestamp.

I then display the information in the "History" section of the web page as follows:

"You travelled (whatever miles) in on (timestamp)."

PROBLEM
Every time I run the application and click 'Stop' to add a new record (i.e. distance, timestamp) to localStorage it overwrites the existing (previous) localStorage data.

I have attempted to put both the distance and timestamp into arrays and push new data into the array but it doesn't work.

AIM
My aim is to produce a list of records. Every time the user clicks 'Stop', their data is added to localStorage and outputted in the "History" section of the web page like this:

"You travelled (whatever miles) in on (timestamp)."
"You travelled (whatever miles) in on (timestamp)."
"You travelled (whatever miles) in on (timestamp)."
"You travelled (whatever miles) in on (timestamp)."
"You travelled (whatever miles) in on (timestamp)."


ANY help or recommendation would be gratefully accepted.
Was This Post Helpful? 0
  • +
  • -

#14 JackOfAllTrades  Icon User is offline

  • Saucy!
  • member icon

Reputation: 6058
  • View blog
  • Posts: 23,495
  • Joined: 23-August 08

Re: HTML5 localStorage Value Array Error

Posted 09 April 2013 - 01:26 PM

Merged topics. There was no point in creating a new topic on the same subject.
Was This Post Helpful? 0
  • +
  • -

#15 Atli  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 3717
  • View blog
  • Posts: 5,979
  • Joined: 08-June 10

Re: HTML5 localStorage Value Array Error

Posted 09 April 2013 - 01:48 PM

View PostLiam O, on 09 April 2013 - 07:16 PM, said:

PROBLEM
Every time I run the application and click 'Stop' to add a new record (i.e. distance, timestamp) to localStorage it overwrites the existing (previous) localStorage data.

I have attempted to put both the distance and timestamp into arrays and push new data into the array but it doesn't work.

View PostAtli, on 03 April 2013 - 12:40 AM, said:

Values stored in the localStorage or sessionStorage are always strings. If you try to store a normal object or array, you will just get the [object Object] or [object Array] strings like you would if you tried to print them.

To store an array in those storage mechanisms, you need to manually convert them to and from a serialized form. The obvious format for Javascript is of course JSON, and that is what you should use.

The code I showed in the rest of that post demonstrates exactly what has to happen if you want to store an array or object inside the Storage mechanisms.

Have you tried implementing this in any way like I demonstrated? There is no sign of it in your jsFiddle code. - If you have but it failed to work, show us the code. We can't help you if you ignore our advice and/or don't show us the things you try.
Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2