I want to...">

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?

+6
source share
2 answers

You can use JSON.parse()

HTML:

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

JQUERY:

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

Screenshot

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 .

 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> 
+6
source

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> 
+13
source

All Articles