How to pass an array into jQuery .data() attribute

JavascriptJqueryHtmlJson

Javascript Problem Overview


Ok so I want to pass a very basic array into a jquery data attrubute server side like so:

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

and then retreive like so:

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

alert(stuff[0]);

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

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

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

Declaring it as an attribute means that it is a string.

So stuff[0] would be equivalent to: var myString = "['a','b','c']"; alert(myString[0]);

You need to make it look like this:

<div data-stuff="a,b,c"></div>

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

Retraction: jQuery's parsing fails because it didn't meet the rules of parseJSON.

However, I will stand behind my solution. There are aspects of the others that are less than ideal, just as this solution is less than ideal in some ways. All depends on what your paradigms are.

Solution 3 - Javascript

As others have identified the value is treated as string so it is returning "[". Please try this (aaa is the name of the div and I took out the data-stuff):

$(function(){
    $.data($("#aaa")[0],"stuff",{"aa":['a','b','c']});
    var stuff = $.data($("#aaa")[0],"stuff").aa;
    alert(stuff[0]); //returns "a"
});

Solution 4 - Javascript

A different approach is posted at jsfiddle; var stuff = $('div').data('stuff'); stuff is a string with 0th character as '['

Well, var stuff = eval($('div').data('stuff')); should get you an array

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionwilsonpageView Question on Stackoverflow
Solution 1 - JavascriptAlnitakView Answer on Stackoverflow
Solution 2 - JavascriptJohn GreenView Answer on Stackoverflow
Solution 3 - JavascriptRajaView Answer on Stackoverflow
Solution 4 - JavascriptMayankView Answer on Stackoverflow