Simplest way to the the id of the selected row.
Simplest way to the the id of the selected row.
phpMick
Posts: 17Questions: 5Answers: 1
Hi,
How can I get the id of the selected row, when I click a button outside of the table?
I added these:
rowId: 'id',
select: true
Then I want to do something like this:
function getSelectedRow(){
var dataTable = $('#users').DataTable();
console.log( dataTable.row().data() );
}
Thanks,
Mick
This discussion has been closed.
Answers
This example shows you how to get the selected row:
https://datatables.net/extensions/select/examples/api/get.html
Kevin
Thanks, I have been looking at that.
How do I then get the rowId?
Try using
row().id()
.Kevin
I was doing like this previously:
This is working:
Is this the best way?
Looks like you are using arrays in which case your config of
rowId: 'id',
isn't doing anything since your data is not object based.I would recommend using
pluck()
if you want to support multiple row selection.You second option will only get one row if multiple are selected. You would use:
table.rows( { selected: true } ).data().pluck(0)
EDIT: The above will return an API object. If you just want an array of the data then add
toArray()
, for example:table.rows( { selected: true } ).data().pluck(0).toArray()
If you change your select extension to support only one row selection then you would use something close to what you have above:
table.row( { selected: true } ).data()[0]
Notice the singular
row
.