I would like to be able to click anywhere on a row and get the contents of its first cell, regardless of where I click. Note that this is a dynamically generated table and consists of <th>
, <tr>
and <td>
elements exclusively (no <tbody>
), and that therefore none of the rows within said table have an id
. The commented part works by itself, so why can't I get the text from that first cell? Or even just the contents of the row would be a good start. Is there something wrong with my selectors anywhere in the function where I'm //trying to get the contents
? I have no clue what's wrong with this.
// Build HTML Table
function buildHtmlTable(portalData, tablename) {
var columns = [];
var headerTr$ = $('<tr/>');
var n = 0;
if (tablename == "order-table") {
document.getElementById("dist-name").innerText = JSON.parse(JSON.stringify(portalData[0], null, 2))["Company Name"];
n = 1;
}
for (var i = 0 ; i < portalData.length ; i++) {
var rowHash = portalData[i];
for (var key in rowHash) {
if ($.inArray(key, columns) == -1) {
columns.push(key);
headerTr$.append($('<th/>').html(key));
}
}
}
$('#' + tablename).append(headerTr$);
for (i = 0 ; i < portalData.length ; i++) {
var row$ = $('<tr/>');
for (var colIndex = n ; colIndex < columns.length ; colIndex++) { // n is how many columns to drop, based on table name
var cellValue = portalData[i][columns[colIndex]];
if (cellValue == null) {
cellValue = "";
}
row$.append($('<td/>').html(cellValue));
}
$('#' + tablename).append(row$);
}
// Drop unnecessary columns
for(i = 0 ; i<n; i++) {
$("#order-table").find('td,th').first().remove();
}
//Trying to get the contents
$(function(){
$("#order-table td").click(function() {
// var column_num = parseInt( $(this).index() ) + 1;
// var row_num = parseInt( $(this).parent().index() );
// alert( "Row_num = " + row_num);
var column = $(this);
var row = ($(this).parent());
alert(row.innerText);
alert(column.innerText);
});
});
}