Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
50
rated 0 times [  51] [ 1]  / answers: 1 / hits: 17944  / 10 Years ago, sat, march 1, 2014, 12:00:00

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?


More From » jquery

 Answers
12

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>




[#72222] Friday, February 28, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ignacio

Total Points: 467
Total Questions: 128
Total Answers: 79

Location: Luxembourg
Member since Tue, Mar 14, 2023
1 Year ago
ignacio questions
;