How can a JavaScript array be stored in an HTML custom data attribute?
I've tried every variation of JSON stringification and escaping characters.
What is the precise method to store the array and retrieve it again?
I build the array with [ $("#firstSelectedElement").val(), $("#secondSelectedElement").val() ]
. I retrieve id="storageElement" data-storeIt="stuff"
with $("#storageElement").data('storeit')
.
I can never seem to retrieve the data as a true array, only an array of characters.
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');
See this JSFiddle demo.
However, escaping isn't necessary. You can do this, instead:
<div id="demo" data-stuff='["some", "string", "here"]'></div>
See this JSFiddle demo.