How can I get all TD data when clicking on TR with jQuery

I have a table with several rows, and I want to get all the TD data after clicking on a specific ROW row.

My table

<table>
 <tr class="person">
   <td class="id">1900</td>
   <td class="name">John</td>
   <td class="gender">Male</td>
 </tr>

 <tr class="person">
   <td class="id">2000</td>
   <td class="name">Pitt</td>
   <td class="gender">Female</td>
 </tr>
</table>

How can I get the id, name, gender after clicking on a string using jQuery.

Ex: If i click on John Row i should get 1900, John, Male and same for Pitt also

thank

+5
source share
5 answers

Here is the solution. You can try find () instead of children ()

$(function(){
    $('.person').click(function(){
        var id = $(this).children('.id').text();
        var name= $(this).children('.name').text();
        var gender = $(this).children('.gender').text();

        alert('Selected ID: ' + id + ', Name: ' + name + ', Gender: ' + gender);
    });

});
+6
source

Update:

To get them separately:

var arr = [];
$('#tableID > tbody > tr').click(function(){
  arr = $(this).find('td').map(function(){
     return this.innerHTML;
  }).get();

  arr = arr.split(',');
  var id = arr[0];
  var name = arr[1];
  var gender = arr[2];
});

You can do:

var arr = [];
$('#tableID > tbody > tr').click(function(){
  arr = $(this).find('td').map(function(){
     return this.innerHTML;
  }).get();

  alert(arr);
});

Check out demo

+3
source
$("tr").bind("click", function(e){
 var id = $(this).find("td.id").text();
 var name = $(this).find("td.name").text();
 var gender = $(this).find("td.gender").text();
});
+1

$(function(){
    $('.person>td').click(function(){
        console.log($(this).parent().children().text());
    })

});
0

, , , tr :

$('.tb_add').click(function ()
{
  var table = $("table tbody");
  table.find('tr').each(function (i) {
        r1 = $(this).find('td').eq(0).text();
        r2 = $(this).find('td').eq(1).text();
        alert(r1+" "+r2);
 });
 });
0

All Articles