Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store and use an array using the HTML data tag and jQuery

I am attempting to store an array in the HTML data tag. For example:

<div data-locs="{'name':'London','url':'/lon/'},{'name':'Leeds','url':'/lds'}"> 

I am accessing that data using jQuery. I realise that this is stored as a string, and I've tried various methods to convert it to an array, but I've hit a wall. If you take a look at this jsFiddle page you'll see a full example of what I'm trying to do.

http://jsfiddle.net/B4vFQ/

Any ideas?

Thanks!

like image 779
will Avatar asked Nov 26 '10 17:11

will


1 Answers

If you use valid JSON ([ and ] for the array, double quotes instead of single), like this:

<div id="locations" data-locations='[{"name":"Bath","url":"/location/bath","img":"/thumb.jpg"},{"name":"Berkhamsted","url":"/location/berkhamsted","img":"/thumb.jpg"}]'> 

Then what you have (using .data()) to get the array will work:

$('#locations').data('locations'); 

You can test it here.

like image 59
Nick Craver Avatar answered Oct 04 '22 04:10

Nick Craver