How to get the Dynamic Table cell value on button click

I’ve a table which is dynamically generated. In its row, I’m placing button.

for (var i = 0; i < resp.length; i++) {    
  tr = tr + "<tr>";    
  tr = tr + "<td >" + resp[i].Date + "</td>";
  tr = tr + "<td >" + resp[i].age + "</td>";
  tr = tr + "<td >" + resp[i].Hour + "</td>";               
  tr = tr + "<td><input value='get me' type='button' class='theButton' id='ma' onclick='test()'></td>";
  tr = tr + "</tr>";

On a button click, I’d like to get the particular cell value of that row. E.g.: If I click on the age in the first row, then the value I have to get is 50. And if I click on the button in second row, then I should get 94.

How can I get the table cell value on a button click & pass it as a argument to function which is on click?

An event listener always has the clicked element as target and the element, that the listener was bound to as context. long story short, when you click on the table cell, the listener’s context is the cell and hence you have access to the cell content.

Add click event to each table cell, and then do something like this:

 $('td').click(function(e) {
    var txt = $(;

or this:

 $('#my-div a').click(function() {
    var txt = $(this).text();

This should accomplish your requirement. Hope this helps.

can be simpilfied to

var txt = this.textContent;

Actually by using this code we are getting values on on clicking table row but what i required is on button click and the button is there at the end of each row on clicking the button then it should get the defined values

So something like in this codepen.

I’ve created two different scripts in this pen.

The first script allows for the column data to be selected and then gets the selected column data from the row of the button clicked.

Whilst the second script will always return the age data when you click on the row button.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.