To append rows to existing table. On each onclick had to pass the selected object.
function populateResult(data, resultElementId){
$.each(data, function(i,row){
$tr = $('<tr><td>'+ row.name+'</td></tr>' ).appendTo(resultElementId);
$tr.on("click", myfunction(row));
});
}
function myfunction(shipObj){
console.log("data :"+JSON.stringify(shipObj));
}
myfunction this method is not invoking on onclick.
Note: I am using jquery 1.7
You can set value of row
as json object i.e :{'datas': row}
inside click event handler and then access this using event object .i.e : e.data.datas
.
Demo Code :
function populateResult(data, resultElementId) {
$.each(data, function(i, row) {
$trs = $(`<tr><td> ${row.name} </td></tr>`).appendTo(resultElementId);
//on click pass that row as well
$trs.on('click', {
'datas': row
}, myfunction);
})
}
function myfunction(e) {
//use event object to access data
console.log('Data : ' + JSON.stringify(e.data.datas));
}
populateResult([{
"name": "s1",
}, {
"name": "s2"
}], "#myTableBody")
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<table>
<tbody id="myTableBody"></tbody>
</table>