user537137
user537137

Reputation: 614

Loop through table and display as Google Chart

I need to get some data out of a table and into a google chart but am getting lost as to how to loop through it correctly

HTML

<tr>
    <th>Date</th>
    <th>Score</th>
    <th>Result</th>
</tr>

    <tr>
        <td class="date">24/12/2012</td>
        <td class="score">51</td>
        <td class="result">30<span class="over"></span></td>
    </tr>

    <tr>
        <td class="date">28/12/2012</td>
        <td class="score">52</td>
        <td class="result">31<span class="over"></span></td>
    </tr>

    <tr>
        <td class="date">02/12/2012</td>
        <td class="score">44</td>
        <td class="result">19<span class="over"></span></td>
    </tr>

Here's the google chart javascript

  google.load("visualization", "1", {packages:["corechart"]});
  google.setOnLoadCallback(drawChart);
  function drawChart() {
    var data = google.visualization.arrayToDataTable([
      ['Date', 'Score', 'Result'],
      [date,  score,      result],
    ]);

I'm guessing I need something like this...

  var date = $this.find(".date").html();
  var score = $this.find(".score").html();
  var result = $this.find(".result").html();

Upvotes: 3

Views: 1899

Answers (1)

davidkonrad
davidkonrad

Reputation: 85538

Do it like this :

var data = new google.visualization.DataTable();
data.addColumn('string','Date');
data.addColumn('number','Score');
data.addColumn('number','Result');

$('table tr').not(':first').each(function(i,tr) {
   data.addRow([
      $(tr).find('.date').text(),
      parseInt($(tr).find('.score').text()),
      parseInt($(tr).find('.result').text())
   ]);
});

We know the column names, so they can be hardcoded. The data is extracted in the loop. Column data is found by class-name, but you could use index as well. Note parseInt to ensure that it actually is numbers being inserted.

enter image description here

However, it could be more generalistic and reuseable if you had a correct formed table structure like

<table>
  <thead>
    <tr>
      <th></th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td></td>
    </tr>
  </tbody>
</table>

Upvotes: 1

Related Questions