Create an Array from a single HTML5 "data-" attribute

Phoenix picture Phoenix · Mar 1, 2014 · Viewed 15k times · Source

I have this HTML:

<section id="SSID" data-texts="'Text1', 'Text2', 'Text3'"></section>

I want to create an Array variable in jQuery and my jQuery code is:

$(document).ready(function() {
    var Selection = $("#SSID").data("texts");
    var Texts = [ Selection ];

    console.log(Texts.length);
});

For my example, the result I expect is:

Texts[0] = 'Text1'
Texts[1] = 'Text2'
Texts[2] = 'Text3'

...and that the length of the array Texts is 3.

However, what I am seeing is that the length of Texts is 1 and that the entire string is being loaded into Texts[0]:

Texts[0] = "'Text1', 'Text2', 'Text3'"

I think my problem is being caused by the " (quotation mark) characters. How can overcome this problem and achieve my objective?

Answer

Tomalak picture Tomalak · Mar 1, 2014

data- attributes can contain JSON.

jQuery will automatically parse them for you, if they are syntactically valid.

<section id="SSID" data-texts='["Text1", "Text2", "Text3"]'></section>

and

$(function() {
    var texts = $("#SSID").data("texts");

    console.log(texts.length);  // logs "3"
});

See: http://jsfiddle.net/5mtre/


Security hint: You must encode the JSON correctly on the server.

This means that you need to do JSON encoding and HTML encoding, here shown examplary using PHP:

<section id="SSID" data-texts="<?=htmlspecialchars(json_encode($data), ENT_QUOTES, 'UTF-8')?>"></section>