My HTML table
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Average</th>
</tr>
</thead>
<tbody id="tableBody">
</tbody>
</table>
Sample table generation
var arrayofObjects = [{sID: 025, name: John Doe, average: 80}, {sID: 893, name: Jane Smith, average: 82}];
function loadTable() {
let table = document.getElementById("tableBody");
table.innerHTML = "";
let tr = "";
vararrayofObjects.forEach(x => {
tr += '<tr>';
tr += '<td><a data-toggle="modal" data-target="#myModal1" id="sIDNum">' + x.sID + '</a></td>' + '<td>' + x.name + '</td>' + '<td>' + x.average + '</td>';
tr += '</tr>'
})
table.innerHTML += tr;
}
What I tried to get value of first column (sID) on click then loop through object array
const tableBody = document.querySelector('#tableBody');
tableBody.addEventListener('click', (e) => {
vararrayofObjects.forEach((element) => {
if(element.sID == $('a').text()) {
var personName = element.name;
var personID = $('#sIDNum').text();
var personAvg = "Average " + element.average;
}
});
});
Problem is that the if statement returns me all values of $('a').text())
instead of the one I clicked on. How do I properly implement it so that clicking on my anchor tag on the first column (sIDNum
) will get its value, then use that value to loop through my object array and get the values of the object that matches with it?