I am storing data using the data- approach in a HTML tag like so:
<td><"button class='delete' data-imagename='"+results[i].name+"'>Delete"</button></td>
I am then retrieving the data in a callback like this:
$(this).data('imagename');
That works fine. What I am stuck on is trying to save the object instead of just one of the properties of it. I tried to do this:
<td><button class='delete' data-image='"+results[i]+"'>Delete</button></td>
Then I tried to access the name property like this:
var imageObj = $(this).data('image');
console.log('Image name: '+imageObj.name);
The log tells me undefined. So it seems like I can store simple strings in the data- attributes but I can’t store JSON objects…
I’ve also tried to use this kid of syntax with no luck:
<div data-foobar='{"foo":"bar"}'></div>
Any idea on how to store an actual object in the HTML tag using the data- approach?
instead of embedding it in the text just use
$('#myElement').data('key',jsonObject);it won’t actually be stored in the html, but if you’re using jquery.data, all that is abstracted anyway.
To get the JSON back don’t parse it, just call:
If you are getting
[Object Object]instead of direct JSON, just access your JSON by the data key: