Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
149
rated 0 times [  151] [ 2]  / answers: 1 / hits: 96658  / 13 Years ago, fri, may 20, 2011, 12:00:00

I want to pass an array into a jQuery data attribute on the server side and then retrieve it like so:




var stuff = $('div').data('stuff');
alert(stuff[0]);

<script src=https://cdnjs.cloudflare.com/ajax/libs/jquery/1.6.1/jquery.min.js></script>
<div data-stuff=['a','b','c']></div>




Why does this appear to alert '[' and not 'a' (see JSFiddle link)


JSFiddle Link: http://jsfiddle.net/ktw4v/3/


More From » jquery

 Answers
28

It's treating your variable as a string, the zeroth element of which is [.



This is happening because your string is not valid JSON, which should use double-quotes as a string delimiter instead of single quotes. You'll then have to use single-quotes to delimit the entire attribute value.



If you fix your quotation marks your original code works (see http://jsfiddle.net/ktw4v/12/)



<div data-stuff='[a,b,c]'> </div>

var stuff = $('div').data('stuff');


When jQuery sees valid JSON in a data attribute it will automatically unpack it for you.


[#92138] Wednesday, May 18, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
mira

Total Points: 460
Total Questions: 108
Total Answers: 99

Location: American Samoa
Member since Fri, Aug 26, 2022
2 Years ago
mira questions
;