0

I'm trying to create and HTML chart with a jquery plugin and I'm using HTML5 data attributes to pass data from my rails app to jquery function.

My html, after the ruby hash conversion, is something like this:

<div class="chart" data-contents-01="0" data-contents-02="1" data-contents-03="3" data-contents-04="0" data-contents-05="0" data-contents-06="0" data-contents-07="0" data-contents-08="0" data-contents-09="0" data-contents-10="0" data-contents-11="0" data-contents-12="0" data-contents-13="0" data-contents-14="0" data-contents-15="0" data-contents-16="0" data-contents-17="0" data-contents-18="0" data-contents-19="0" data-contents-20="0" data-contents-21="0" data-contents-22="0" data-contents-23="2" data-contents-24="1" data-contents-25="4" data-contents-26="0" data-contents-27="0" data-contents-28="0" data-contents-29="2" data-contents-30="2" data-contents-31="0" id="chart_2" style="padding: 0px; position: relative;">

I have a lot if data-contents-xx and I must convert this data to an array of array.

My function take data as:

 var contents = [
                    [x, y],
                    [x,y]
                ];

so I must process my data attributes to have an array of array, where each sub-array is a couple of data-contents-x

How can i serialize my data attribute?

Roberto Pezzali
  • 2,484
  • 2
  • 27
  • 56
  • 1
    This answer might put you on the right track: http://stackoverflow.com/questions/2224933/iterating-over-element-attributes-with-jquery – lesssugar May 26 '14 at 19:59
  • I try but I cant figure how to iterate between data-contents-xx With ruby for me is easy, with jquery no! Is there something like a map method to build an array of array? – Roberto Pezzali May 26 '14 at 20:28
  • Do you need to serialize to separate data-* attributes? Both Rails and jQuery can handle a single data attribute with a json encoded array of values. – James Mason May 26 '14 at 21:12

1 Answers1

0

The JQuery method .data() will pull all data objects into an array of key: value pairs. With your element names:

$('.chart').data();

For example, given:

<div class="chart" data-foo="1" data-bar="2"></div>

Use:

var data = $('.chart').data();

for(var i in data){
    console.log("data attribute - " + i + ":" + data[i]);
}

Here's the fiddle: http://jsfiddle.net/WVfSg/260/

When playing with your code in the fiddle, it doesn't work. However, when I get rid of the second hyphen, it works as expected.

steel
  • 11,883
  • 7
  • 72
  • 109
  • I try but is not working. `$('.chart').data();` return me `Object {plot: Plot, resizeSpecialEvent: Object}` – Roberto Pezzali May 27 '14 at 08:12
  • Okay, I've adjusted the code and added a link to the fiddle. Your div configuration isn't working it looks like because of the second hyphen in your data names. – steel May 27 '14 at 13:23