To create tr & td dynamically and append to table. Onclick pass the json selected object

872 Views Asked by At

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

2

There are 2 best solutions below

0
On BEST ANSWER

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>

1
On

There's many ways to achieve what you need. Here's two:

Assign the click handler to a delegator parent

$("#table tbody").on("click", "tr", function() {
  // get the tbody TR index and that's its position in the data array
  const idx = $(this).index();
  const row = data[idx];
  myfunction(row);
});

or

Create TRs with a click handler already assigned

function populateResult(data, resultElementId) {
  $.each(data, (i, row) => $("<tr>", {
    html: `<td>${row.name}</td>`,
    appendTo: resultElementId,
    click() {
      myfunction(row)
    }
  }));
}

Demo of the last example:

function populateResult(data, resultElementId) {
  $.each(data, (i, row) => $("<tr>", {
    html: `<td>${row.name}</td>`,
    appendTo: resultElementId,
    click() {
      myfunction(row)
    }
  }));
}

function myfunction(shipObj) {
  console.log("data :" + JSON.stringify(shipObj));
}

const data = [{name:"Lorem"}, {name: "Ipsum"}];
populateResult(data, "#myTableBody");
<table>
  <tbody id="myTableBody"></tbody>
</table>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>