PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, November 8, 2022

[FIXED] How to pass data onclick event in dynamically created row in table by for loop in JQuery?

 November 08, 2022     dom, dom-manipulation, html, javascript, jquery     No comments   

Issue

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


Solution

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>



Answered By - Rory McCrossan
Answer Checked By - Terry (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing