Row Grouping in datatables not working - javascript

I have been trying to follow this approach of row grouping described in the following link. http://www.datatables.net/examples/advanced_init/row_grouping.html
However while implementing the drawCallback function I had to change the name to "fnDrawCallback" for my datatable to recognize this function and also declare var api as var api = this.oApi._fnGetTrNodes( settings ); instead of the way described in the example (var api = this.api();) as otherwise I was getting an error. However now I am still getting a similar error while defining the rest of function if I follow the syntax and keywords given in the example. That is ,
var rows = api.rows( {page:'current'} ).nodes();
var last=null;
api.column(2, {page:'current'} ).data().each( function ( group, i ) {
if ( last !== group ) {
$(rows).eq( i ).before(
'<tr class="group"><td colspan="5">'+group+'</td></tr>'
);
The error I get is "undefined is not a function " for the drawCallback function. I tried a lot trying to find a different way of writing the same function but I cannot understand why this doesn't work and why I had to change the api declaration too.
I am very new to this , so if someone could explain what the correct format would be to write this function without this error I would really appreciate it !
Please find my Jquery part listed below. Thanks in advance !!
$(document).ready(function(){
var oTable = $("#tableTenants").dataTable({
"bProcessing": true,
"sAjaxSource": "/api/alltenantstatistic.json?iDisplayStart=0&iDisplayLength=${totalCount}&sSortDir_0=asc",
"aoColumns": [
{ "mDataProp": "state","sClass": "student_rows" , "sWidth":"1%" },
{ "mDataProp": "name","sClass": "student_rows" , "sWidth":"20%"},
{ "mDataProp": "testAdmin","sClass": "student_rows" , "sWidth":"70%"},
{ "mDataProp": "totalStudentCount","sClass": "select_rows" , "sWidth":"2%", "bSortable": false },
{ "mDataProp": "totalPnPStudentCount","sClass": "select_rows" , "sWidth":"2%", "bSortable": false }
],
"aoColumnDefs": [
{ "fnRender": function(oObj) {
return '' + oObj.aData.state + '';
},
"bUseRendered": false,
"aTargets": [0]
},
{
"aTargets": [1],
"bVisible": false
},
],
"iDisplayLength": 10,
"order": [[ 1, 'asc' ]],
"fnDrawCallback": function ( settings ) {
console.log("hello");
var api = this.oApi._fnGetTrNodes( settings ); // Had to change this from this.api();
var rows = api.rows({page:'current'}).nodes(); // Giving an error
var last=null;
api.column(1, {page:'current'} ).data().each( function ( group, i ) {
if ( last !== group ) {
$(rows).eq( i ).before(
'<tr class="group"><td colspan="4">'+group+'</td></tr>'
);
last = group;
}
} );
},
"bLengthChange": true,
"bFilter": true,
"bAutoWidth": false,
//"bStateSave": true,
"sDom": "<'row-fluid'<'span5'l><'span7'f><'span2'>r>t<'row-fluid'<'span6'i><'span6'p>>",
"sPaginationType": "bootstrap",
"oLanguage": {
"sLengthMenu": "_MENU_",
"sEmptyTable": "No Organization Uploads available for this Tenant",
"sInfoEmpty": "",
"sProcessing": "Loading..."
}
});

Its due to jquery datatable version problem. use below libraries and code
<script src="//cdn.datatables.net/1.10.2/js/jquery.dataTables.min.js"></script>
<script src="//cdn.datatables.net/plug-ins/725b2a2115b/integration/bootstrap/3/dataTables.bootstrap.js"></script>
<script src="//datatables.net/release-datatables/extensions/ColReorder/js/dataTables.colReorder.js"></script>
"drawCallback": function (settings) {
var api = this.api();
var rows = api.rows({ page: 'current' }).nodes();
var last = null;
api.column(1, { page: 'current' }).data().each(function (group, i) {
if (last !== group) {
$(rows).eq(i).before(
'<tr class="group"><td colspan="3">' + group + '</td></tr>'
);
last = group;
}
});
},

Related

Apply column search to current jQuery DataTable

I have a current jQuery DataTable in place that is functioning properly:
var $dataTable = $('#example1').DataTable({
"ajax": 'api/tableSearch.php',
"iDisplayLength": 25,
"order": [[ 6, "desc" ]],
"scrollY": 600,
"scrollX": true,
"bDestroy": true,
"columnDefs": [{
"targets": 0,
"render": function (data, type, full, meta){
return '<a class="editLink" href="#">Edit</a><a class="deleteLink" href="#">Del</a>':
}
}]
});
As stated, the above code works accordingly...the search filter works, the sorting works, everything works.
What I would like to do is add a column search to this datatable, as shown here:
https://www.datatables.net/release-datatables/examples/api/multi_filter_select.html
I attempted to add the code from the link above to my current code, as follows:
var $dataTable = $('#example1').DataTable({
"ajax": 'api/tableSearch.php',
"iDisplayLength": 25,
"order": [[ 6, "desc" ]],
"scrollY": 600,
"scrollX": true,
"bDestroy": true,
"columnDefs": [{
"targets": 0,
"render": function (data, type, full, meta){
return '<a class="editLink" href="#">Edit</a><a class="deleteLink" href="#">Del</a>':
}
}], // begin here
initComplete: function(){
this.api().columns().every(function(){
var column = this;
var select = $('<select><option value=""></option></select>')
.appendTo( $(column.footer()).empty() )
.on( 'change', function () {
var val = $.fn.dataTable.util.escapeRegex(
$(this).val()
);
column
.search( val ? '^'+val+'$' : '', true, false )
.draw();
} );
column.data().unique().sort().each( function ( d, j ) {
select.append( '<option value="'+d+'">'+d+'</option>' )
} );
} );
}
} );
});
I have not received any errors, and the DataTable still loads, but the column search is not there.
I am using jQuery-2.1.3.min, so it should be up to date.
Does anyone see what I am doing wrong and what I can do to correct this issue?
Add a <tfoot> to your table. The expression referencing column.footer() expects it to exist.

Sorting on a column in removing html contents in Datatables 1.10

I am unsing datatable 1.10, In my code in one of the column as per the requirement I am adding an HTML checkbox tag.
Now first time when the table gets rendered it shows me those checkboxes but when I click on that column to sort or any other column for sorting then the column which contains HTML contains are getting wiped out. (I crosschecked this with the chrome DOM inspector... the td element contains nothing :()
Below is my dataTable initialization code.
dataTableOptions: function() {
return {
"orderable": true,
"columnDefs": undefined,
"autoWidth": true,
"deferRender": true,
"data": undefined
};
},
dtRowGroupingOptions: function () {
return {
bExpandableGrouping: true,
bExpandSingleGroup: false,
iExpandGroupOffset: -1,
asExpandedGroups: [""]
};
}
var dataTablesOptions = self.dataTableOptions();
dataTablesOptions.data = tableData;
dataTablesOptions["paginate"] = false;
dataTablesOptions["lengthChange"] = false;
dataTablesOptions["columnDefs"] = [{"targets": 0, "data": "serverName", 'title' : 'ServerName'},
{"targets": 1, "data": "COMMAND", 'title' : 'Command'},
{"targets": 2, "data": "PID", 'title' : 'Process Id'},
{"targets": 3, "data": "SIZE", 'title' : 'Size'},
{"targets": 4, "data": "USER", 'title' : 'User'},
{"targets": 5, "data": "action", 'title' : 'Actions', "type" : "html", "orderDataType": "dom-checkbox"}
];
dataTablesOptions["createdRow"] = function (nRow, aData, iDataIndex) {
var self = this;
if (aData["comments"] && aData["comments"].indexOf("Error") != -1) {
// Do not do anything
$('td:eq(0)', nRow).html(aData["serverName"]+"" +
"<a class='btn btn-danger' href='#' data-toggle='tooltip' title='Error in execution'><i class='icon-question'></i></a>");
}
return self;
};
var dcInfoDataTable = contentDiv.find('table.dcInfoTable').DataTable(dataTablesOptions);
I am also using datatables rowGrouping and searchhiglight plugin, below is the code.
// call row grouping
contentDiv.find('table.dcInfoTable').dataTable().rowGrouping(self.dtRowGroupingOptions());
// enable search highlighing
contentDiv.find('table.dcInfoTable').dataTable().fnSearchHighlighting();
Note: I tried removing rowGrouping plugin code just to make sure that this is not happeing because of this plugin but even after removing there is no effect, the HTML contents are getting wiped out.
Not only when you sort will it clear out your data, it will also clear it if you use any other feature that changes your table. This happens because each time the datatable draws for new data, it's clearing out your static data.
You need to re-append the checkboxes on each draw, you can do this in the fnDrawCallback event:
$(document).ready( function() {
$('#example').dataTable( {
"fnDrawCallback": function( oSettings ) {
alert( 'DataTables has redrawn the table' );
//append the checkbox to your table columns here...
}
} );
} );

jQuery Datatables.net - refresh table - getting null sAjaxSource

I have the following function which should update a datatable in my ASP.NET site master page:
function refreshTable(oTable) {
var table = $(oTable).dataTable();
var oSettings = table.fnSettings();
//Retrieve the new data with $.getJSON. You could use it ajax too
$.getJSON(oSettings.sAjaxSource, null, function (json) {
table.fnClearTable(this);
for (var i = 0; i < json.aaData.length; i++) {
table.oApi._fnAddData(oSettings, json.aaData[i]);
}
oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();
table.fnDraw();
});
}
This function is then called to refresh a table if an attachment is added to the site - this is the datatable settings that it should refresh.
var DeleteClicked = false;
var oTable;
$(document).ready(function () {
oTable = $('#infoTable').dataTable({
"aaSorting": [[6, "desc"]],
"bProcessing": true,
"sAjaxSource": '/Web/Handlers/infoTableHandler.ashx',
"aoColumns": [
{ "mData": "ID", "bVisible": false },
{ "mData": "Type" },
{ "mData": "Received" },
{
"mData": "Action", "sWidth": "100px", "mRender": function (data, type, row) {
var id = row.ID;
return "<input type=button id=" + id + " onclick='DeleteFile(" + id + ")' class=buttonBlue value=Delete />";
},
},
{ "mData": "IsImage", "bVisible": false }
],
"bDeferRender": true,
});
However - if I open Developer Tools in Chrome I get an error message saying sAjaxSource is null so i cannot then get the value from it - so oSettings is null and then I cannot get access to the sAjaxSource - anyone see anything wrong here?
you're basically reinitializing your dataTable in the first row of refreshTable. Try instead:
function refreshTable() {
var oSettings = oTable.fnSettings();
...
}
and refer directly to the global oTable instead of your local table variable

jQuery DataTables fnRender Increment Column

I'm trying to create a row inside my datatable that increments +1 each row. I've been told the easiest way to do this would be using fnRender. Now I've used fnRender to change data that's already in a column from the serverside processor, but never to create a new column alone.
Any help would be awesome!
Here's my current code:
oTable = $('#testingz').dataTable({
"bProcessing": true,
"bServerSide": true,
"bJQueryUI": true,
"sPaginationType": "full_numbers",
"aaSorting": [ [1,'desc'] ],
"sDom": '<""l>rt<"F"fp>',
"sAjaxSource": "server_processing.php",
"aoColumnDefs": [
{
"fnRender": function ( o, val ) {
return '' + o.aData[0] + '';
},
"aTargets": [ 0 ]
}
]
});
Do you mean something like this: http://datatables.net/release-datatables/examples/api/counter_column.html

need help with editable tables in jQuery ( DataTables plugin )

I'm trying to use jQuery and its plugin DataTables ( http://www.datatables.net/release-datatables/examples/api/editable.html ), to make an editable table.
Here's my code so far. The top part of it works great by generating a table inside a DIV with the data from a js array.
Yet I also need this table to be editable. I have found an example code for it ( see bottom part ) but kinda can't figure out how to apply it to my table?
Any ideas? Thanks!
$(document).ready(function() {
$('#dynamic').html( '<table cellpadding="0" cellspacing="0" border="0" class="display" id="example"></table>' );
/// create a table within the '#dynamic' DIV
$('#example').dataTable( {
"aaData": numbarr, /////// takes data from the 'numbarr' js array.
"aoColumns": [
{ "sTitle": "Country " }, //// column names
{ "sTitle": "Number " },
{ "sTitle": "Tariff ID " },
{ "sTitle": "Customer Acc " },
{ "sTitle": "Customer Name " },
{ "sTitle": "Payment Terms " },
{ "sTitle": "Payout/Call " },
{ "sTitle": "Payout/Min " },
]
} );
///////////////////////////// the code above workd fine!
////////////////// this code was taken from an example, not sure how to connect it with my table...
$('td', oTable.fnGetNodes()).editable( '../examples_support/editable_ajax.php', {
"callback": function( sValue, y ) {
var aPos = oTable.fnGetPosition( this );
oTable.fnUpdate( sValue, aPos[0], aPos[1] );
},
"submitdata": function ( value, settings ) {
return {
"row_id": this.parentNode.getAttribute('id'),
"column": oTable.fnGetPosition( this )[2]
};
},
"height": "12px"
} );
////////////////// this code was taken from an example, not sure how to connect it with my table...
I've used this plugin http://square-bracket.com/openjs
The example I see states to initialize your table like:
$('#example').dataTable(options).makeEditable(options);
That being said, I haven't gotten it to work yet either.
This is an example that works for me:
$('#tblDataTable2').dataTable({
"bJQueryUI": true,
"sPaginationType": "full_numbers",
"aaSorting": [[ 0, "asc" ]],
"aoColumnDefs": [
{ "sClass": "center", "aTargets": [ 0, 1 ] }
]
}).makeEditable({
sAddURL: "Setting?operation=create",
sUpdateURL: "Setting?operation=update",
"aoColumns": [
{ placeholder: '' },
{ placeholder: '' }
],
});

Categories

Resources