Search code examples
javascriptjquerygoogle-visualizationgoogle-datatable

how to assign values to TR in google dashboard table


i am using Google Dashboard's table functionality, i want to assign value of id to tr of each row that is created, i have array as follows

   var data = google.visualization.arrayToDataTable([
      ['Name', 'Donuts eaten','id'],
      ['Michael' , 5,'1'],
      ['Elisa', 7,'2'],
      ['Robert', 3,'3'],
      ['John', 2,'4'],
      ['Jessica', 6,'5'],
      ['Aaron', 1,'6'],
      ['Margareth', 8,'7']
    ]);

      var table = new google.visualization.ChartWrapper({
                    'chartType': 'Table',
                    'containerId': 'chart2',
                    dataTable: data,
                    'options': {
                        'width': '500px'
                    }
                });
                table.draw();

I am still unable to figure out if there is some way to bind values to DOM elements any help will be appreciated.


Solution

  • Here's one solution, using JQuery:

    google.visualization.events.addListener(table, 'ready', function () {
      $('#chart2 .google-visualization-table-tr-odd, #chart2 .google-visualization-table-tr-even').each(function (e) {
          var idx = $('td:nth-child(2)', this).html();
          $(this).attr('id', 'row' + idx);
        });
      });
    

    And to remove the ID column:

    google.visualization.events.addListener(table, 'ready', function () {
      $('.google-visualization-table-tr-head td:nth-child(3)').remove();
      $('#chart2 .google-visualization-table-tr-odd, #chart2 .google-visualization-table-tr-even').each(function (e) {
          var td = $('td:nth-child(2)', this)
          var idx = td.html();
          td.remove();
          $(this).attr('id', 'row' + idx);
        });
      });
    

    With sorting taken into account:

    function tableCleanUp() {
      google.visualization.events.addListener(table.getChart(), 'sort', tableCleanUp2);
      tableCleanUp2();
    }
    
    function tableCleanUp2() {
      $('.google-visualization-table-tr-head td:nth-child(3)').remove();
      $('#chart2 .google-visualization-table-tr-odd, #chart2 .google-visualization-table-tr-even').each(function (e) {
          var td = $('td:nth-child(2)', this)
          var idx = td.html();
          td.remove();
          $(this).attr('id', 'row' + idx);
        });
    }
    
    google.visualization.events.addListener(table, 'ready', tableCleanUp);