user537137
user537137

Reputation: 614

Get sum of table column and add to google chart

I need to get the sum of a column from multiple (5) tables and add these sums to 5 instances in a google pie chart. The code I have is pretty close I think but just can't work out where I am going wrong.

function drawChart() {

      // calculate the sum of each table
      function sum($inputs) {
        var sum=0;
        //iterate through each input and add to sum
        $inputs.each(function() {     
                sum += parseInt($(this).text());                      
        });         

        var data = google.visualization.arrayToDataTable([
          ['Type', 'Cost'],
          ['Expense',     sum($('#expenses .amount'))],
          ['Savings',      sum($('#savings.amount'))],
          ['Commute',  2],
          ['Watch TV', 2],
          ['Sleep',    7]
        ]);

        var chart = new google.visualization.PieChart(document.getElementById('piechart_3d'));
        chart.draw(data, options);
      }
    }

Upvotes: 0

Views: 1208

Answers (2)

anurupr
anurupr

Reputation: 2344

You need to return the sum value in the function sum.

function drawChart() {

  // calculate the sum of each table
  function sum($inputs) {
    var sum=0;
    //iterate through each input and add to sum
    $inputs.each(function() {     
            sum += parseInt($(this).text());                      
    });
    return sum;
 }         

    var data = google.visualization.arrayToDataTable([
      ['Type', 'Cost'],
      ['Expense',     sum($('#expenses .amount'))],
      ['Savings',      sum($('#savings.amount'))],
      ['Commute',  2],
      ['Watch TV', 2],
      ['Sleep',    7]
    ]);

    var chart = new google.visualization.PieChart(document.getElementById('piechart_3d'));
    chart.draw(data, options);

}

Upvotes: 1

Florian Gl
Florian Gl

Reputation: 6014

Try the following:

 function drawChart() {

  // calculate the sum of each table
  function sum($inputs) {
    var sum=0;
    //iterate through each input and add to sum
    $inputs.each(function() {     
            sum += parseInt($(this).text());                      
    });         
    return sum;
  }
    var data = google.visualization.arrayToDataTable([
      ['Type', 'Cost'],
      ['Expense',     sum($('#expenses .amount'))],
      ['Savings',      sum($('#savings.amount'))],
      ['Commute',  2],
      ['Watch TV', 2],
      ['Sleep',    7]
    ]);

    var chart = new google.visualization.PieChart(document.getElementById('piechart_3d'));
    chart.draw(data, options);
}

Upvotes: 1

Related Questions