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

Issue

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/

Solution

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.

Answered By – Alnitak

Answer Checked By – David Marino (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.