Create an array of one HTML5 data- attribute
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:
$(document).ready(function() { var Selection = $("#SSID").data("texts"); var Texts = [ Selection ]; console.log(Texts.length); }); In my example, I expect:
Texts[0] = 'Text1' Texts[1] = 'Text2' Texts[2] = 'Text3' ... and that the length of the Texts 3 array.
However, I see that the length of Texts 1 and that the entire line is loaded into Texts[0] :
Texts[0] = "'Text1', 'Text2', 'Text3'" I think my problem is caused by the characters " (quotation marks). How can I overcome this problem and achieve my goal?
You can use JSON.parse()
HTML:
<section id="SSID" data-texts='"Text1", "Text2", "Text3"'></section> JQUERY:
var Selection = JSON.parse('[' + $("#SSID").data("texts") + ']'); 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 keep the actual JSON as the value of the data attribute. For example, data-texts='["Text1", "Text2", "Text3"]' and data-texts='["Text1", "Text2", "Text3"]' it directly.
UPDATE: Or you can do it with Array#map and String#split .
data- attributes may 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 tip: you should correctly encode JSON on the server.
This means that you need to do JSON encoding and HTML encoding, an example using PHP is shown here:
<section id="SSID" data-texts="<?=htmlspecialchars(json_encode($data), ENT_QUOTES, 'UTF-8')?>"></section>