Phoenix Phoenix - 6 months ago 14
Javascript Question

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

I have this following 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);
});


I want to get the results which will denote
Texts[0] = Text1
,
Text[1] = Text2
,
Text[2] = Text3
etc. And so, the content length should be
3
.

This length seems to be
1
, because it detects the whole thing into
Texts[0]
. It shows
Text[0]
containing the string
"'Text1', 'Text2', 'Text3'"
.

How to overcome this issue which I think is being caused by the
"
(quotation) symbols?

Answer

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"));
Comments