Clicking on a row, I get id is undefined
Clicking on a row, I get id is undefined
YoDavish
Posts: 123Questions: 46Answers: 3
I have JSON data that is passed into DataTables. Each row is clickable, I want it to pass the the "id" from the row into a function that will perform an Ajax call (query function). However, I'm unable to get the "id" from the row itself. When I click on the row the alert pops up with "undefined id"
Below is my code.
[code]
// READY FUNCTION
$(document).ready(function() {
var obj = $('#tempDataForm').serializeJSON();
query('discrepancyList',obj,refreshDiscrepancyTable,0,"queryDiscrepancy.php");
});
function refreshDiscrepancyTable(response) {
if(response.result.state == 'success') {
var refreshedData = response.result.data.results;
var colNames = response.result.data.colNames;
console.log(colNames);
if ( $.fn.DataTable.isDataTable('#discrepancyQueue') ) {
$('#discrepancyQueue').DataTable().destroy();
}
$('#discrepancyQueue').DataTable( {
data: refreshedData,
// fnDrawCallback function
"fnDrawCallback": function( oSettings ) {
```$('#discrepancyQueue').on( 'click', 'tr', function () {
var table = $('#discrepancyQueue').DataTable();
// Gets the row id value
var id = table.row( this ).id();
console.log("ID is "+id);
alert( 'Clicked row id '+id );
});```
},
columns: colNames,
// Datatables extension that will optimize table layout for different screen size through dynamic insertion and removal of columns from the table
responsive: true,
// Hides "Id" columns and makes it not searchable
"columnDefs": [
{
"targets": [ 0 ],
"visible": false,
"searchable": false
}
]
} );
var myTable = $('#discrepancyQueue').DataTable();
notify('success','Test!');
} else {
notify('warn','Error!');
}
}
[/code]
This question has an accepted answers - jump to answer
This discussion has been closed.
Answers
I think the problem is that you don't have the
rowId
setup. Therow().id()
docs state that is will use the value ofrowId
. TherowId
docs state that it will default toDT_RowId
if it is an object in your data. Otherwise you need to define it based on a column with unique data.Kevin
Try
I've updated the code to try to get the ".data().id;"
But still no luck, it still says "Undefined Id". The column Name is "Id" so I tried .data()Id as well but still no luck.
Code updated below:
var table = $('#discrepancyQueue').DataTable();
// Gets the row id value
var id = table.row( this ).data().id;
alert( 'Clicked row id '+id );
Do you have a column
id
in yourcolumns: colNames,
definition?var id = table.row( this ).data().id;
would look forid
defined incolumns.data
. You can use something else from yourcolumns.data
.Kevin
I got it to work now. Rather than targeting the specific column, I just got the entire data in the row and looked for the first column. Below is how it got it to work, even when the column itself is hidden.