Simplest way to the the id of the selected row.

Simplest way to the the id of the selected row.

phpMickphpMick 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

Answers

  • kthorngrenkthorngren Posts: 21,300Questions: 26Answers: 4,945

    This example shows you how to get the selected row:
    https://datatables.net/extensions/select/examples/api/get.html

    Kevin

  • phpMickphpMick Posts: 17Questions: 5Answers: 1

    Thanks, I have been looking at that.

    How do I then get the rowId?

  • kthorngrenkthorngren Posts: 21,300Questions: 26Answers: 4,945

    Try using row().id().

    Kevin

  • phpMickphpMick Posts: 17Questions: 5Answers: 1
    edited March 2018

    I was doing like this previously:

    table.rows( { selected: true } ).data()[0].id
    

    This is working:

    table.rows( { selected: true } ).data()[0][0]
    

    Is this the best way?

  • kthorngrenkthorngren Posts: 21,300Questions: 26Answers: 4,945
    edited March 2018

    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.

This discussion has been closed.