In order to effectively come up with a solution to the problem, we must store the table data and the table object in arrays. We first create arrays for the data and the table object at the top of the page.
var tableData=new Array();
var table=new Array();
var tableid=0;
We then generate our table storing them in arrays referenced by a unique identifier. Then in order to fulfill the select functionality of the table we add a listener to the table object. We then grab the id of the containing div of the table, and take the substring of that id to discover what table has just been clicked. Then we take the row of that table as normally done using the method .getSelection(). Once we have both the row and the table id we can return those to the users based on which table and row he clicked.
//create dynamic number of tables
for (id=0;id<num_of_tables;id++) {
var tableID = 'table_div' + id; //The id of the google visualization table
//Generate the div for the google visualization table
$('<div/>', {
id: tableID,
class: 'cd_table'
}).appendTo('#tables');
listData = data;
if (listData[id].length>0) {
tableData[id] = new google.visualization.DataTable();
tableData[id].addColumn('string', 'name');
tableData[id].addColumn('string', 'email');
for (var i=0; i<listData[id].length; i++) {
tableData[id].addRows(1);
tableData[id].setCell(i,0,listData[id][i].name);
tableData[id].setCell(i,1,listData[id][i].email);
}
}
table[id] = new google.visualization.Table(document.getElementById(tableID));
table[id].draw(tableData[id], {showRowNumber: false, sortColumn: 0});
google.visualization.events.addListener(table[id], 'select', function() {
$(document).on('mousemove', '.google-visualization-table', function() {
tableid=$(this).closest('.cd_table').attr('id').substring(9);
});
var row;
if (table[tableid].getSelection()[0] != undefined) {
row = table[tableid].getSelection()[0].row;
lastRowClick = row;
} else row = lastRowClick;
alert('table id:' + tableid + ' row:' + row);
});
}
This is nearly perfect, but only works if you clicked on the table already once. We must also add a mousemove event in the initial page load jquery function, like so:
$(document).on('mousemove', '.google-visualization-table', function() {
tableid=$(this).closest('.cd_table').attr('id').substring(9);
});
And done. You are able to create an unlimited amount of dynamically generated google visualization tables, that can return the row clicked and the id of the table that was clicked.