-1

I have a table that is populated dynamically. I need to get data of a cell on clicking it .How can that be done.

I am populating the table in following manner :-

 function fetchAllRecords() {
    $('#tab_logic').empty();
    var html="";
    html+="<thead> <tr>  <th scope='col'>Order Id</th> <th scope='col'>Latitude/Longitude</th> <th scope='col'>OTP</th> <th scope='col'>Call Status</th> <th scope='col'>Call Duration</th> <th scope='col'>Call Unit</th> </tr> </thead> <tbody> ";
    for (var i = 1; i <= 6; i++) {
      html+="<tr> <td onclick='tableFunction()'> <p id='trow"+i+"'> Data</p></td> <td> <p> Data </p></td> <td> <p> Data </p></td> <td> <p> Data </p></td> <td> <p> Data </p></td> <td> <p> Data </p></td></tr>"
    }
    html+="</tbody>";
    $('#tab_logic').append(html);

    }

I tried getting the data like this but it didn't work

function tableFunction(){
    var txt = $(this).text();
    alert(txt);

    }
Aman Kumar Sinha
  • 407
  • 6
  • 17

2 Answers2

2

You need to pass this as an argument to the function.

      html+="<tr> <td onclick='tableFunction(this)'> <p id='trow"+i+"'> Data</p></td> <td> <p> Data </p></td> <td> <p> Data </p></td> <td> <p> Data </p></td> <td> <p> Data </p></td> <td> <p> Data </p></td></tr>"

and then use a function parameter

function tableFunction(element) {
    var txt = element.innerText;
    alert(txt);
}

But instead of using inline JavaScript, I recommend you use event delegation in jQuery. See Event binding on dynamically created elements?

Barmar
  • 741,623
  • 53
  • 500
  • 612
0

This can be simply achieved by using .On() for selecting dynamically created rows.

$(document).on('click','td',function() {
 alert($(this).text());
});

I would suggest instead of directly targeting the td, adding separate class for the dynamically created td and calling them by this class name will be better.