Home > Software engineering >  How to pass data onclick event in dynamically created row in table by for loop in JQuery?
How to pass data onclick event in dynamically created row in table by for loop in JQuery?

Time:11-09

I have an array of objects like

const array = [{id:1,name:'a'},{id:2,name:'b'},{id:3,name:'c'}]

The HTML snippet is

<table id="NameTable">
  <thead>
    <tr>
          <th>Name</th>
     </tr>
   </thead>
   <tbody>
   </tbody>
</table>

Now I am populating the table from the array data (above given) dynamically.

array.foreach(person=> {
$("NameTable tbody").append(`<tr><td>   ${person.name} </td></tr>` )

It works properly and data is loaded in table. Now I want to call a function on row click by passing argument of person for example. i want this function to be called on row click

function call(personObj){
   console.log(personObj)
}

Now this function should be called on each row click and only relevant data should be passed to call function. How can I get this through JQuery

CodePudding user response:

To achieve your goal you can use jQuery's data() method to store each object as a reference to the td you create. You can then retrieve it from the td when it's clicked. Something like this:

const array = [{ id: 1, name: 'a'}, { id: 2, name: 'b' }, { id: 3, name: 'c' }]
const $table = $('#NameTable');

array.forEach(person => {
  const $tr = $('<tr />');
  const $nameTd = $('<td />').text(person.name).data('person', person).appendTo($tr);
  $table.find('tbody').append($tr);
});

$table.on('click', 'td', e => { 
  const $td = $(e.currentTarget);
  const personObj = $td.data('person');
  console.log(personObj);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<table id="NameTable">
  <thead>
    <tr>
      <th>Name</th>
    </tr>
  </thead>
  <tbody></tbody>
</table>

  • Related