Skip to content
Advertisement

Why is my .data() function returning [ instead of the first value of my array?

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/

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/)

<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.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement