Mike
Mike

Reputation: 105

Get row id of a table row after selecting a row and clicking the button in datatables

What I want to achieve is to display a table and after selecting a row, make it possible to edit or delete a row (make a proper query) so I need a primary key which I don't want to display. My table looks like this:

<table id='documents_d' class='display'>
    <thead>
        <tr><th>title 1</th><th>title 2</th><th>title 3</th>
    </thead>
    <tbody>
        <tr data-id='1'>
            <td>content</td>
            <td>content</td>
            <td>content</td>
        <tr data-id='2'>
            <td>content</td>
            <td>content</td>
            <td>content</td></tr>
    </tbody>
</table>

I use the following script to get the datatables running:

<script>
    $(document).ready(function () {
        var documents_d = $('#documents_d').DataTable({
            paging: true,
            dom: 'Blfrtip',
            colReorder: true,
            select: {style: 'single'},
            rowId: 'Writer',
            buttons: [
                'colvis',
                'excelHtml5',
                {
                    text: 'Edit',
                    action: function () {
                        alert(documents_d.row('.selected').data());
                    }
                }
            ]
        });
    });
</script>

Instead of an alert I want to run a function like editDocument($docID). So first I want to select a row (this is working fine) and after clicking 'Edit' I want to get the 'data-id' and run a function. I tried:

documents_d.row('.selected').data("data-id")

but this would give me an error:

DataTables warning: table id=documents_d - Requested unknown parameter '7' for row 1, column 7. For more information about this error, please see http://datatables.net/tn/4

Upvotes: 2

Views: 2381

Answers (1)

thirtydot
thirtydot

Reputation: 228302

You probably want this:

$(documents_d.row('.selected').node()).data('id');

However, there's another way:

https://datatables.net/reference/option/rowId

It can often be useful to have a id attribute on each tr element in a DataTable for row selection and data source identification, particularly when using events.

Then you can use:

documents_d.row('.selected').id();

Upvotes: 1

Related Questions