I want to pass an array into a jQuery data attribute on the server side and then retrieve it like so:
JavaScript
x
2
1
var stuff = $('div').data('stuff');
2
alert(stuff[0]);
JavaScript
1
2
1
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
2
<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/
Advertisement
Answer
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/)
JavaScript
1
4
1
<div data-stuff='["a","b","c"]'> </div>
2
3
var stuff = $('div').data('stuff');
4
When jQuery sees valid JSON in a data attribute it will automatically unpack it for you.