How to get the data object on click the cell.I have created the table and used datatable.I want to get the geography and customer type from the cell click I have tried as
$('#table tbody').on( 'click','td', function () {
//alert ('clicked');
//var data1 = table.row().data();
var data1 = table.row( $(this).parents('tr') ).data();
console.log(data1);
alert( data1[0] +"'s Customer type: "+ data1[ 2 ] );
} );
my table id is table and I got the response as below in console for console.log(data1);
{Geography: "APAC", Current: "0", CustomerType: "AMRevenue", DSO: "0", OverDue: "0"}
getting undefined for data1[0] how to get the geo and customer type
Advertisement
Answer
If you add a click event on td and click on each td, you can be able to get the value of that td‘s data by using $(this).text();. Have a look at the snippet below and after running the snippet click on the td and see the value.
$("#myTable tbody td").click(function () {
console.log($(this).text());
});<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<table class="table" id="myTable">
<thead>
<tr>
<th>FirstName</th>
<th>LastName</th>
</tr>
</thead>
<tbody>
<tr>
<td>John</td>
<td>Doe</td>
</tr>
<tr>
<td>Jane</td>
<td>Burl</td>
</tr>
</tbody>
</table>Update: If you click on a specific row and want to get the entire row’s data you can simply follow this way:
$("#myTable tbody td").click(function () {
var row = $(this).closest("tr"); // Find the row
var cell1 = row.find("td:nth-child(1)").text(); // Find the first cell's data
var cell2 = row.find("td:nth-child(2)").text(); // Find the second cell's data
console.log(cell1 + " " + cell2);
});<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<table id="myTable">
<thead>
<tr>
<th>FirstName</th>
<th>LastName</th>
</tr>
</thead>
<tbody>
<tr>
<td>John</td>
<td>Doe</td>
</tr>
<tr>
<td>Jane</td>
<td>Burl</td>
</tr>
</tbody>
</table>