I have a datatable that is created with Ajax. However, I do not want all the fields to be displayed and thus I set bVisible to false on the not-so-important field.
get current tr data using following code(also returns hidden columns value perfectly):
$('#example-table-id').dataTable().fnGetData($('currenttr'));
it returns an array and you can access to td values like follow:
$('#example-table-id').on('click', 'tbody tr', function(){
var arr=$('#example-table-id').dataTable().fnGetData($(this));
var Id=arr[0]; //returns first td value
var Name=arr[1];//returns second td value
}
I would recommend something like this:
var data = [];
$.ajax({url:"../DataQueries/FetchAllSubjectsForBrowse.asp",success:function(result){
data=result;
}});
var i=0;
data.forEach(function(d) {d.index=i++;});
$('#example').dataTable( {
"bProcessing": true,
"aaData":data,
"aoColumns": [
/*index*/
/* Subject Name */ null,
/* Address */ null,
/* LinkedWithCompany */ { "bVisible": false},
/* Work Tel */ null
]
} );
Then in your click handler get the index and then access the record in your original data array
$('#example tbody tr').live('click', function () {
var sTitle;
var nTds = $('td', this);
var index = $(nTds[0]).text();
var record = data[i];
});
This is just a starting point, but I hope you get the idea.
On the Datatables v1.10.x I've used this method:
Column definition:
"columnDefs": [
{ "data": "yourColumnId", "targets": 0, "visible": false
]
And then in my function...
var rows = $("#tbl").dataTable().fnGetNodes();
for (var i = 0; i < rows.length; i++) {
id = $("#tbl").dataTable().fnGetData(i).yourColumnId;
}
I prefer this method instead of the:
id = $(rows[i]).find("td:eq(0)").html();
Here is an example of getting row's data on a click.
Suppose you have Delete or any button with each row of the table and if you click on the button, get the data of the selected row and perform required operation.
$(document).ready(function(){
$('#example tbody').on('click', '.delete', function(){
var row = $(this).closest('tr');
var data = $('#example').dataTable().fnGetData(row);
console.log(data);
});
});