Reputation: 15660
I'm trying to familiarize myself with the jquery dataTables plug in: http://www.datatables.net/manual/server-side#Sent-parameters
What's Working
I have json data being returned from the server to my client and the table is being populated.
What's Not working
I need to be able to capture the data in a given row, when the row is selected / clicked on by the end user.
Here's my code: http://jsfiddle.net/e3nk137y/1515/
$("#users tr").click(function(){
alert($(this).find("pID").val());
});
The above javascript is what I've been playing around with. Trouble is that the ajax call happens automagically and I'm not the one creating the rows in the table. Ultimately, I need to be able to grab some of the fields in each row, in addition to the ID / pID
What I've tried so far
Besides the playing with the javascript code, I've also been reviewing this: http://datatables.net/examples/api/select_single_row.html But in that example, all the data is defined client side, so it makes it easy to specify either an id or a class for each table row
Any suggestions would be appreciated.
Upvotes: 8
Views: 49952
Reputation: 2713
var Table = $('#CheckinTable').DataTable( {
// optional info
});
$('#CheckinTable tbody').on('click', 'tr', function () {
let bookingData = Table.row(this).data();
// do your staff
});
Upvotes: 1
Reputation: 17550
Errors in your fiddle:
tr
as selector in the on()
method.find()
an element by id you need to use the #
. But beware that you can't use ids if there are multiple elements, use a class instead.text()
instead of val()
.Updated function:
$("#users").on('click', 'tr', function () {
alert($(this).find("#pID").text());
});
Upvotes: 3
Reputation: 1870
Hope this is what you r looking for
Html
<table id="users" class="display" width="100%" cellspacing="0">
<thead>
<tr>
<th id="pID">ID</th>
<th>Name</th>
<th>Code</th>
<th>Available</th>
</tr>
</thead>
<tbody>
<tr>
<td>1-1</td>
<td>1-2</td>
<td>1-3</td>
<td>1-4</td>
</tr>
<tr>
<td>2-1</td>
<td>2-2</td>
<td>2-3</td>
<td>2-4</td>
</tr>
</tbody>
<tfoot>
<tr>
<th>ID</th>
<th>Name</th>
<th>Code</th>
<th>Available</th>
</tr>
</tfoot>
</table>
Script
$(document).ready(function () {
var table = $('#users').DataTable();
$('#users tbody').on('click', 'tr', function () {
console.log(table.row(this).data());
});
});
Upvotes: 20