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

16,298

Solution 1

You can use JSON.parse()

HTML :

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

JQUERY :

var Selection = JSON.parse('[' + $("#SSID").data("texts") + ']');

Fiddle Demo

or

HTML :

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

JQUERY :

var Selection = JSON.parse($("#SSID").data("texts"));

FYI : But it would be better to store the actual JSON as the data attribute value. For eg : data-texts='["Text1", "Text2", "Text3"]' and parse it directly.


UPDATE : Or you can do it using Array#map method and String#split method.

var Selection = $("#SSID").data("texts").split(',').map(JSON.parse);

console.log(Selection);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<section id="SSID" data-texts='"Text1", "Text2", "Text3"'></section>

Solution 2

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>
Share:
16,298
Phoenix
Author by

Phoenix

Updated on June 17, 2022

Comments

  • Phoenix
    Phoenix almost 2 years

    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?