store and retrieve javascript arrays into and from HTML5 data attributes
The HTML5 data attribute can store only strings, so if you want to store an array you will need to serialize it. JSON will work and it looks like you're on the right path. You just need to use JSON.parse()
once you retrieve the serialized data:
var retrieved_string = $("#storageElement").data('storeit');
var retrieved_array = JSON.parse(retrieved_string);
Reviewing the api documentation, jQuery should try to automatically convert a JSON encoded string provided it is properly encoded. Can you give an example of the value you are storing?
Also note that HTML5 data attribute and jQuery .data()
methods are two distinct things. They interact, but jQuery is more powerful and can store any data type. You could just store a javascript array directly using jQuery without serializing it. But if you need to have it in the markup itself as an HTML5 data attribute, then you are limited only to strings.
For the record, it didn't work with encoded entities for me, but seems that in order to be parsed as an object, the data attribute must be a well formed JSON object.
So I was able to use an object with:
data-myarray="{"key": "value"}"
or maybe just use single quotes:
data-myobject='{"key1": "value1", "key2": value2}'
Time to have fun! :D
It turned out that you could use the html escaped characters in the element data
attribute to have json-like array (encoded are quotes):
<div id="demo" data-stuff='["some", "string", "here"]'></div>
And then in javascript get it without any additional magic:
var ar = $('#demo').data('stuff');
Check this fiddle out.
Edited (2017)
You don't need to use html escaped characters in the data
attribute.
<div id="demo" data-stuff='["some", "string", "here"]'></div>
Check this new fiddle out.
It depends on what type of data you're storing in the array. If it's just strings (as it appears to be) and you have a character that you know will never be a part of your data (like the comma in my example below) then I would forget about JSON serialization and just use string.split:
<div id="storageElement" data-storeIt="stuff,more stuff"></div>
Then when retrieving:
var storedArray = $("#storageElement").data("storeIt").split(",");
It will handle a bit better than using JSON. It uses less characters and is less "expensive" than JSON.parse
.
But, if you must, your JSON implementation would look something like this:
<div id="storageElement" data-storeIt='["hello","world"]'></div>
And to retrieve:
var storedArray = JSON.parse($("#storageElement").data("storeIt"));
Notice that in this example we had to use semi-quotes ('
) around the data-storeIt
property. This is because the JSON syntax requires us to use quotes around the strings in its data.