ifischer ifischer - 2 months ago 12
jQuery Question

Add jquery datatables table footer via Javascript without using HTML

I define my jquery datatables without any HTML besides the base table element. This is my HTML:

<table id="mytable"></table>


Then I do all the table configuration via the datatables definition. Example code:

var dataSet = [
{name: "storage101", size: 492},
{name: "storage102", size: 742},
{name: "storage103", size: 423}
]

$.extend($.fn.dataTable.defaults, {
sDom: '<"top"i>rCt<"bottom"flp><"clear">'
});

$("#storages").dataTable({
data: dataSet,
aoColumns: [
{title: "Name", mData: "name"},
{title: "Size", mData: "size"}
],
oLanguage: {sEmptyTable: "No logs"},
fnFooterCallback: function(nRow, aaData, iStart, iEnd, aiDisplay) {
var api = this.api();
var size = 0;
aaData.forEach(function(x) {
size += (x['size']);
});
// I need a footer in my table before doing this, what is the smartest way to add the footer?
$(api.column(1).footer()).html(
size
);
}
});


Now I would like to use the footer callback to show sums of my dataset inside the footer.

Unfortunately, adding HTML to the footer (like in this example: https://datatables.net/examples/advanced_init/footer_callback.html) does not work as the table does not contain any tfoot element and the required row and columns.
What would be a clean way to add footer for all my columns?

JSFiddle with the code above:
http://jsfiddle.net/36twp251/1/

Answer

As the other answers say I need to define the footer beforehands somehow. Not perfect, but at least I can keep my HTML clean (just defining table and its id but nothing more):

// globally defined table to be reused in several views
$.fn.storageTable = function() {
    $(this).append("<tfoot><tr><td></td><td></td></tr></tfoot>")
    return this.dataTable({
        data: dataSet,
        aoColumns: [
            {title: "Name", mData: "name"},
            {title: "Size", mData: "size"}
        ],
        oLanguage: {sEmptyTable: "No logs"},
        fnFooterCallback: function(nRow, aaData, iStart, iEnd, aiDisplay) {
            var api = this.api();
            var size = 0;
            aaData.forEach(function(x) {
                size += (x['size']);
            });
            $(api.column(1).footer()).html(size);       
        }
    });
}

// sample usage
$("table-storages").storageTable();

JSFiddle: http://jsfiddle.net/ifischer/Ljwgrkq0/3/

Comments