Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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/

like image 980
wilsonpage Avatar asked May 20 '11 12:05

wilsonpage


People also ask

How pass data attribute value in jQuery?

$('selector expression'). attr('name','value'); First of all, specify a selector to get the reference of an element and call attr() method with attribute name parameter. To set the value of an attribute, pass value parameter along with name parameter.

Can we store array in data attribute?

You can use arrays and hashes in HTML5 data attributes. Use JSON. parse, and make sure you're using single quotes around the brackets and double quotes inside the brackets.

How get data attribute from Element?

First, select the element which is having data attributes. We can either use the dataset property to get access to the data attributes or use the . getAttribute() method to select them by specifically typing their names.

Can data attributes be used with JavaScript?

HTML data-* Attributes The data-* attributes gives us the ability to embed custom data attributes on all HTML elements. The stored (custom) data can then be used in the page's JavaScript to create a more engaging user experience (without any Ajax calls or server-side database queries).


2 Answers

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.

like image 60
Alnitak Avatar answered Oct 03 '22 20:10

Alnitak


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.

like image 28
John Green Avatar answered Oct 03 '22 21:10

John Green