Google Visualization - Select Handler not working

Viewed 109

I'm hoping this is a problem that's really easy to fix. Having copied all of the necessary code from the Google Visualization site, everything is working with one exception. I have a data table where, if I select a row, the select handler is called - but I am unable to get table.getSelection() to work

I've seen a suggestion that I might need to include getChart(), but that doesn't fix it (at least not in any of the ways I tried).

In the extract below, I get the first alert message when selecting a row, but not the second, as the code stops running at the table.getSelection() line.

Can anyone suggest what the problem might be?

Many thanks!

<html>

</body>

<head>

<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['table']});
google.charts.setOnLoadCallback(drawTable_1);

function drawTable_1() {

js_booking = <?php echo json_encode($arr_booking); ?>;
js_name = <?php echo json_encode($arr_name); ?>;

var data = new google.visualization.DataTable();
data.addColumn('string', 'Booking');

data.addColumn('string', 'Name');

for (i = 0; i < 5; i++) {

data.addRows([
[js_booking[i], js_name[i]]
]);

}

var table = new google.visualization.Table(document.getElementById('table_div_1'));

table.draw(data, {showRowNumber: false, sort: 'disable', width: '95%', allowHtml:true});

google.visualization.events.addListener(table, 'select', selectHandler);
}

function selectHandler(e) {

alert('A table row was selected');

var selection = table.getSelection();

alert('Selection identified');

}

</script>

</head>
<body>
<div id="table_div_1">Loading...</div>
</body>

<br>

</html>

1 Answers

don't really see a problem with the code, seems to work fine here.

only minor issue...
generally, chart events should be assigned after the chart is created but before the chart is drawn.

see following working snippet...

google.charts.load('current', {
  packages: ['table']
}).then(function drawChart() {

  var data = new google.visualization.DataTable();
  data.addColumn('string', 'Booking');
  data.addColumn('string', 'Name');
  
  for (var i = 0; i < 5; i++) {
    data.addRow(['Booking ' + (i + 1), 'Name ' + (i + 1)]);
  }


  var table = new google.visualization.Table(document.getElementById('table_div_1'));

  google.visualization.events.addListener(table, 'select', selectHandler);

  table.draw(data, {showRowNumber: false, sort: 'disable', width: '95%', allowHtml:true});

  function selectHandler(e) {
    console.log('A table row was selected');
    var selection = table.getSelection();
    console.log('Selection identified', JSON.stringify(selection));
  }
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="table_div_1"></div>

Related