will
will

Reputation: 4575

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!

Upvotes: 46

Views: 75179

Answers (4)

Jules Colle
Jules Colle

Reputation: 11939

If for whatever reason you insist on using double quotes, you will need to html encode the quotes in your data attribute.

<div data-dwarfs="[&quot;Doc&quot;, &quot;Sneezy&quot;, &quot;Happy&quot;]"></div>

Of course if you have access to PHP or some other pre-processor, you could use something like this:

<?php
    $dwarfs = ['Doc', 'Sneezy', 'Happy'];
?>
    <div data-dwarfs="<?php echo htmlspecialchars(json_encode($dwarfs), ENT_QUOTES, 'UTF-8') ?>"></div>
<?php

Upvotes: 0

Nick Craver
Nick Craver

Reputation: 630379

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.

Upvotes: 90

jwueller
jwueller

Reputation: 30996

Try adding [ and ] to beginning and end (this makes it valid JSON). After doing so, you can use JSON.parse() to convert it to a native JavaScript object.

Upvotes: 6

cambraca
cambraca

Reputation: 27839

Try this:

var testOne = eval("new Array(" + $('#locations').data('locations') + ")");

Look at it in jsfiddle.

Upvotes: -3

Related Questions