Add table footer with Javascript only

Add table footer with Javascript only

ifischerifischer Posts: 6Questions: 1Answers: 1

I prefer to define my tables without using any HTML besides the base table element and do all the work inside the jquery-datatables definition.

I also use colvis to toggle column visibility.

What would be a clean way to add the footer HTML via Javascript, so I can fill it inside the fnFooterCallback?
In which callback should I do it?

This question has an accepted answers - jump to answer

Answers

  • ifischerifischer Posts: 6Questions: 1Answers: 1
  • allanallan Posts: 61,920Questions: 1Answers: 10,153 Site admin

    You need to add the footer before you create the table as DataTables doesn't provide a method for creating a footer at the moment. You could use something like:

    $("#storages").append(
        $('<tfoot/>').append( $("#storages thead tr").clone() )
    );
    

    But you need to create the header before the table is initialised as well! Or just put it in the HTML.

    Allan

  • ifischerifischer Posts: 6Questions: 1Answers: 1
    Answer ✓

    Thanks Allen!
    Unfortunately I cannot simply clone the header as I need an empty footer but a sum column in one row.

    This is how I did it in the end - as you said I need to add the footer beforehands:

    javascript:

    // 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();
    

    Demo fiddle:
    http://jsfiddle.net/ifischer/Ljwgrkq0/3/

    Not perfect, but at least I can keep my HTML file "clean". Since I reuse the table in many different views, I would always have to change each HTML separately which is prone to errors.

  • allanallan Posts: 61,920Questions: 1Answers: 10,153 Site admin

    Thanks for posting back - good ot hear you got it working!

    Allan

This discussion has been closed.