1

I have the code to total a column, but I have subgroups that already have totals. Can I total each number in the column EXCEPT the gray total rows? enter image description here

var table = $('#datatable');
var leng = table.find("tr:first").children().length;

    // add totals to new row
            for (var i = 0; i < leng; i++) {

                var total = api
                .column(i)
                .data()
                    .reduce(function (a, b) {
                        // return if it's not a value from the gray row
                        return intVal(a) + intVal(b);
                    });

                // correct any html mistakes that slip through
                if (isNaN(intVal(total)))
                    total = '';

                table.find("tfoot tr:first th").eq(i).html(total);
            };
3
  • maybe the grey rows have a specific class? Commented Sep 4, 2015 at 12:37
  • They do, but how would that look code wise? The class is 'sgrouptotal' Commented Sep 4, 2015 at 12:43
  • use .not('.sgrouptotal') to exclude everything that have class sgrouptotal Commented Sep 4, 2015 at 16:13

2 Answers 2

2

Why not just use the :not selector on the rows() API method and calculate the sum based on the remaining rows? Very small example, add the sum of col#1 to the footer in a callback :

var table = $('#example').DataTable({
    drawCallback: function () {
        var api = this.api(),
            sum = 0;
        api.rows(":not('.sgrouptotal')").every(function() {
            sum += parseFloat(this.data()[0]);
        });    
        $(api.column(0).footer()).text(sum);
    }
});

demo -> http://jsfiddle.net/j38bmagj/

The above should be fairly easy to extend to multiple columns. Calculate the sum for col #4 in the same loop like sum4 += this.data()[4] and so on.

Sign up to request clarification or add additional context in comments.

Comments

0

What about just doing that?

i = 0;          
$('#datatable tr:first tr').each(function(key, value){
    if(!$(this).hasClass("sgrouptotal"){
        i += parseInt(value.text());
    }
});

1 Comment

This doesn't work because i refers to the columns, of which there is 4 - not the 12 rows.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.