Craig van Tonder
Craig van Tonder

Reputation: 7687

DataTables - Getting the database ID of the current row via click event

I am trying to get the database ID of the current row while clicking a button.

I have seen a few examples relating to this aspect and have tried many but it seems that they mostly relate to the legacy table tools extension whereas I am making use of the Editor.

Using the idSrc option from the Editor manual I recieve a server side response in JSON that contains the databases id/primary key value:

{
  "data":[
    {
      "id":"1",
      "name":"Test Name",
    }
  ],
  "options":[],
  "files":[]
}

Now I am trying to get that value by clicking a button that is attached to row via the API function: row().id()

Within the example for this function it provides a clear example of how the rows id value (now the database id?) can be obtained:

var table = $('#myTable').DataTable();
$('#myTable').on( 'click', 'tr', function () {
  var id = table.row( this ).id();
  alert( 'Clicked row id '+id );
});

So I have implemented this as follows:

var editor;
$(document).ready(function() {

  editor = new $.fn.dataTable.Editor( {
    ajax: "/names.php",
    table: "#example",
    idSrc: "id",
    fields: [ {
      label: "Name:",
      name: "name"
    } ]
  });

  var table = $('#example').DataTable( {
    dom: "Bfrtip",
    ajax: "/names.php",
    columns: [
      { data: "name" }
    ]
  });

  $('#example').on( 'click', 'tr', function () {
    var id = table.row( this ).id();
    alert( 'Clicked row id ' + id );
  });

});

The problem here though is that when I click on the row (tr) it prompts as follows: Clicked row id undefined

Why am I getting back an undefined value when it should be sending back the row id?

Upvotes: 0

Views: 1969

Answers (2)

Craig van Tonder
Craig van Tonder

Reputation: 7687

As @CMedina pointed out, rowId stipulates which value in the JSON data is used as each rows id attribute.

Here is the code used to get the rows ID value which is prefixed with row_:

$('#example').on( 'click', 'tr', function () {
  // Get the rows id value
  var id = table.row( this ).id();
  // Filter for only numbers
  id = id.replace(/\D/g, '');
  // Transform to numeric value
  id = parseInt(id, 10);
  // So instead of returning the actual id which is row_1
  // We get back just the primary key which is 1
  alert( 'Clicked row id '+id );
});

Upvotes: 0

CMedina
CMedina

Reputation: 4222

When instances your DataTable, you must indicate the id field rowId, which should be indicated as the name of your columns

var table = $('#example').DataTable( {
dom: "Bfrtip",
ajax: "/names.php",
columns: [
  { data : "id" },//id is the name of your data
  { data: "name" }
],
rowId: 'id' //Here assign the id to your table
});

Result: https://jsfiddle.net/cmedina/7kfmyw6x/17/

Upvotes: 2

Related Questions