Getting the database ID of the current row via click event

Getting the database ID of the current row via click event

icdebicdeb Posts: 20Questions: 5Answers: 0

I am trying to get the database ID of the current row via a click event.

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 receive 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? What is the correct way to do this?

This question has an accepted answers - jump to answer

Answers

  • icdebicdeb Posts: 20Questions: 5Answers: 0

    Realised that the missing link here is: https://datatables.net/reference/option/rowId

    I needed to set the rows id attribute using rowId and then getting the primary key value was easy:

    $('#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);
      alert( 'Clicked row id '+id );
    });
    

    Please mark this as closed.

  • allanallan Posts: 63,542Questions: 1Answers: 10,476 Site admin
    Answer ✓

    Yup - that's the one. If you didn't want to set the rowId option for whatever reason you could also use table.row( this ).data().id.

    Thanks for the update and good to hear you got it fixed.

    Allan

  • icdebicdeb Posts: 20Questions: 5Answers: 0

    That is much easier, thanks!

This discussion has been closed.