I am using jQuery datatable.I done it using http://www.datatables.net/examples/api/select_row.html Now I want to get selected row values ids
Script:
$(document).ready(function() {
var table = $('#example').DataTable();
$('#example tbody').on( 'click', 'tr', function () {
$(this).toggleClass('selected');
} );
$('#button').click( function () {
alert( table.rows('.selected').data().length +' row(s) selected' );
} );
} );
And HTML Code:
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Id</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Id</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</tfoot>
<tbody>
<tr>
<td>1</td>
<td>System Architect</td>
<td>Edinburgh</td>
<td>61</td>
<td>2011/04/25</td>
<td>$320,800</td>
</tr>
<tr>
<td>2</td>
<td>Accountant</td>
<td>Tokyo</td>
<td>63</td>
<td>2011/07/25</td>
<td>$170,750</td>
</tr>
</table>
Now I am able to get selected no.of.rows.Now I want to get selected row Ids.Can anyone guide me to achieve it.
It can be useful to provide the user with the option to select rows in a DataTable. This can be done by using a click event to add / remove a class on the table rows. The rows(). data() method can then be used to get the data for the selected rows.
click(function (){ var dataArr = []; var rowCount = table. rows('. selected'). data().
You can iterate over the row data
$('#button').click(function () { var ids = $.map(table.rows('.selected').data(), function (item) { return item[0] }); console.log(ids) alert(table.rows('.selected').data().length + ' row(s) selected'); });
Demo: Fiddle
More a comment than an answer - but I cannot add comments yet: Thanks for your help, the count was the easy part. Just for others that might come here. I hope that it will save you some time.
It took me a while to get the attributes from the rows and to understand how to access them from the data() Object (that the data() is an Array and the Attributes can be read by adding them with a dot and not with brackets:
$('#button').click( function () { for (var i = 0; i < table.rows('.selected').data().length; i++) { console.log( table.rows('.selected').data()[i].attributeNameFromYourself); } } );
(by the way: I get the data for my table using AJAX and JSON)
var table = $('#myTableId').DataTable();
var a= [];
$.each(table.rows('.myClassName').data(), function() {
a.push(this["productId"]);
});
console.log(a[0]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With