I'm trying to create a dynamic HTML table in lightning component, but have issues on capturing the clicked record from the table. Can someone please suggest what approach should I take. In the below code Event is returning to null and would like to fetch the record which I clicked on for further processing.
Ex: when I click on United Oil & Gas, UK need to get the AccountId of respective Account.
({
createTable : function(component, event, helper) {
var JSONResult;
var action = component.get("c.getAccount");
action.setCallback(this, function(response){
JSONResult = response.getReturnValue();
var col = [];
var colwithHeaderName = [];
var table = document.createElement("table");
table.setAttribute("class", "slds-table slds-table_bordered slds-table_cell-buffer slds-scrollable_x");
var tr = table.insertRow(-1);
console.log('**col**'+col);
for (var i = 1; i < col.length; i++) {
var th = document.createElement("th");
th.setAttribute("class","slds-text-title_caps");
var colHeaderName=col[i];
if(colHeaderName.indexOf("__c")>-1) colHeaderName=colHeaderName.substring(0,colHeaderName.indexOf("__c"));
if(colHeaderName.indexOf("_")>-1) colHeaderName=colHeaderName.replace("_"," ");
th.innerHTML = colHeaderName;
colwithHeaderName.push(colHeaderName);
tr.appendChild(th);
}
for (var i = 0; i < JSONResult.length; i++) {
tr = table.insertRow(-1);
for (var j = 1; j < col.length; j++) {
var tabCell = tr.insertCell(-1);
if(j==1){
var aLink = document.createElement("a");
aLink.setAttribute("value",JSONResult[i][col[j]]);
aLink.setAttribute("data-record",j);
aLink.setAttribute("data-recId",JSONResult[i][col[0]]);
aLink.innerHTML=JSONResult[i][col[j]];
var recordId=JSONResult[i][col[0]];
var index=i;
aLink.setAttribute("id",recordId);
aLink.addEventListener("click", function(component,event){
// Would like fetch the record Id of the selected record from dataTable
});
tabCell.appendChild(aLink);
}
else{
tabCell.innerHTML = JSONResult[i][col[j]];
}
}
}
});
$A.enqueueAction(action);
},
readTable : function(component, event, helper) {
//Read table rows
var staticTableDOM=document.getElementById('divTest').getElementsByTagName('table')[0];
console.log('*** Table ***');
console.log(staticTableDOM);
console.log('*** Table Rows ***');
console.log(staticTableDOM.rows);
console.log('*** Table 1st Row cells ***');
console.log(staticTableDOM.rows[0].cells);
}
})