ToddN
ToddN

Reputation: 2961

Google Visualization Chart throw alert on Select Event Data

I am attempting to use Googles Visualization column charts to simply throw an alert when a specific column is selected. Ie. I want to do something (throw an alert) when Company1's column data is selected:

      google.load("visualization", "1", {packages:["corechart"]});
      google.setOnLoadCallback(drawChart);
      function drawChart() {
        var data = new google.visualization.DataTable();
        data.addColumn('string', 'Date');
        data.addColumn('number', 'Company1');
        data.addColumn('number', 'Company2');
        data.addColumn('number', 'Company3');
        data.addColumn('number', 'Company4');
        data.addColumn('number', 'Company5');
        data.addColumn('number', 'Company6');
        data.addRows([
          ['Feb 1, 2012 - Mar 13, 2012', 10, 10, 5, 15, 10, 55]

        ]);

        var options = {
          title: 'Total Reviews',
          hAxis: {title: '',  titleTextStyle: {color: 'blue'}}
        };

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

google.visualization.events.addListener(chart, 'select', function() {
 //SOMETHING GOES HERE WHEN ie. Company1 is selected, probably an IF but I cant seem to let it know when Company1 is selected.
 alert('Company1 was selected!');       

}

Upvotes: 0

Views: 3196

Answers (1)

Juan Mellado
Juan Mellado

Reputation: 15113

You must call getSelection function to retrieve the current selection. Selection is an array of objects. Each object have row and column attributes (if any). Use the column one to retrieve the label name:

google.visualization.events.addListener(chart, 'select', function() {
  var selection = chart.getSelection()[0];
  var label = data.getColumnLabel(selection.column);

  if (label === "Company1"){
    alert("!");
  }
});

Documentation (follow the link to read more):

selection_array: An array of selected objects, each one describing a data element in the underlying table used to create the visualization (a DataView or a DataTable). Each object has properties row and/or column, with the index of the row and/or column of the selected item in the underlying DataTable. If the row property is null, then the selection is a column; if the column property is null, then the selection is a row; if both are non-null, then it is a specific data item. You can call the DataTable.getValue() method to get the value of the selected item. The retrieved array can be passed into setSelection()

Upvotes: 3

Related Questions