Recalculate sum of columns when hide a column in dynamic table with pagination

Recalculate sum of columns when hide a column in dynamic table with pagination

huashengsuhuashengsu Posts: 1Questions: 1Answers: 0

I tried to solve this problem more than a week, but still can not figure out, I really hope and appreciate if someone can help me find a solution.

I used DataTables in my website (WordPress). There's a table, last column of this table will calculated the sum of previous three columns, i.e. column 7= column 6 + column 5 + column 4. When I hide a column (e.g. column 4), I expect column 7 can recalculate the new sum of previous columns, i.e. now column 7 = column 6 + column 5. So, here is my currently solution:

$(document).ready(function() {
  var x = setInterval(function(){
    $('#table_1 tbody tr').each(function(){
    var sum = 0;
    $(this).find('td.needcalculate').each(function(){
    sum += parseInt($(this).html());
    });
    $(this).find('td.lastcolumn').html(sum);
    });  
  },17);
});

However, it is work for recalculate, but not work for ordering columns, if I descending ordering last column, it will not work well. So I insert a new ordering function (found in stackoverflow).Now code is:

$(document).ready(function() {
  var x = setInterval(function(){
    $('#table_1 tbody tr').each(function(){
    var sum = 0;
    $(this).find('td.needcalculate').each(function(){
    sum += parseInt($(this).html());
    });
    $(this).find('td.lastcolumn').html(sum);
    });  
  },17);
  var f_nm = -1; // flag to toggle the sorting order
  $("th.lastcolumnhead").click(function(){
  f_nm *= -1; // toggle the sorting order
  var n = $(this).prevAll().length;
  sortTable(f_nm,n);
  });
});
function sortTable(f,n){
  var rows =  $('#table_1').DataTable()
  .rows()
  .nodes();
  rows.sort(function(a, b) {
    var A = getVal(a);
    var B = getVal(b);
    if(A < B) {return -1*f;}
    if(A > B) {return 1*f;}
    return 0;
  });
  function getVal(elm){
    var v = $(elm).children('td').eq(n).text().toUpperCase();
    if($.isNumeric(v)){
        v = parseInt(v,10);
    }
    return v;
  }
  $.each(rows, function(index, row) {
    $('#table_1').children('tbody').append(row);   
  });
}

So after that, ordering columns work well now. But only in current page of this table.When I go to next page of this table, the ordering column will chaos again. I tried to instead

setInterval()

to

on ( 'click', function ()) 

however it will still recalculated the currently page, not work well if I go to next page of table.

So I didn't find a good solution for dynamic table with pagination. Can someone help me? I uploaded to jsfiddle:
jsfiddle.net/sttdds7c/13/

This discussion has been closed.