0

I am trying to transfer selected rows from one table to another and than get last column values sum.

I use footerCallback to show sum:

$(document).ready(function() {
    $('#table2').DataTable( {
        "footerCallback": function ( row, data, start, end, display ) {
            var api = this.api(), data;
 
            // Remove the formatting to get integer data for summation
            var intVal = function ( i ) {
                return typeof i === 'string' ?
                    i.replace(/[\$,]/g, '')*1 :
                    typeof i === 'number' ?
                        i : 0;
            };
 
            // Total over all pages
            total = api
                .column( 8 )
                .data()
                .reduce( function (a, b) {
                    return intVal(a) + intVal(b);
                }, 0 );
 
            // Total over this page
            pageTotal = api
                .column( 8, { page: 'current'} )
                .data()
                .reduce( function (a, b) {
                    return intVal(a) + intVal(b);
                }, 0 );
 
            // Update footer
            $( api.column( 8 ).footer() ).html(
                '$'+pageTotal +' ( $'+ total +' total)'
            );
        }
    } );
} );

For transferring i use this code:

function tab1_To_tab2()
            {
            var table1 = document.getElementById("table1"),
                    table2 = document.getElementById("table2"),
                    checkboxes = document.getElementsByName("check-tab1");
            console.log("Val1 = " + checkboxes.length);
                 for(var i = 0; i < checkboxes.length; i++)
                     if(checkboxes[i].checked)
                        {
                            // create new row and cells
                            var newRow = table2.insertRow(table2.length),
                                cell1 = newRow.insertCell(0),
                                cell2 = newRow.insertCell(1),
                                cell3 = newRow.insertCell(2),
                                cell4 = newRow.insertCell(3);
                                cell5 = newRow.insertCell(4);
                                cell6 = newRow.insertCell(5);
                                cell7 = newRow.insertCell(6);
                                cell8 = newRow.insertCell(7);
                                cell9 = newRow.insertCell(8);
                               
                            // add values to the cells
                            cell1.innerHTML = table1.rows[i+1].cells[1].innerHTML;
                            cell2.innerHTML = table1.rows[i+1].cells[2].innerHTML;
                            cell3.innerHTML = table1.rows[i+1].cells[3].innerHTML;
                            cell4.innerHTML = table1.rows[i+1].cells[4].innerHTML;
                            cell5.innerHTML = table1.rows[i+1].cells[5].innerHTML;
                            cell6.innerHTML = table1.rows[i+1].cells[6].innerHTML;
                            cell7.innerHTML = table1.rows[i+1].cells[7].innerHTML;
                            cell8.innerHTML = table1.rows[i+1].cells[8].innerHTML;
                            cell9.innerHTML = table1.rows[i+1].cells[9].innerHTML;
                           
                            
                           
                            // remove the transfered rows from the first table [table1]
                            var index = table1.rows[i+1].rowIndex;
                            table1.deleteRow(index);
                            // we have deleted some rows so the checkboxes.length have changed
                            // so we have to decrement the value of i
                            i--;
                           console.log(checkboxes.length);
                           
                        }
                        
            }

But after transferring rows goes under tfoot and sum does not come up, see PIC.

PIC

Here is a full code, config.php uses AJAX to path data:

//config.php
$(document).ready(function() {
    $.ajax({
        type: "GET",
        url: "backend-script.php",
        dataType: "html",
        success: function(data) {
            $("#table-container").html(data);
        }
    })
});

//Base Code
<div align="center">  
                     <input type="text" name="search" id="search" class="form-control" />  
                </div>  
                <br />
<?php
include("config.php");
$db=$con;
// fetch query
function fetch_data(){
 global $db;
  $query="SELECT * from realizacia ORDER BY id DESC";
  $exec=mysqli_query($db, $query);
  if(mysqli_num_rows($exec)>0){
    $row= mysqli_fetch_all($exec, MYSQLI_ASSOC);
    return $row;  
        
  }else{
    return $row=[];
  }
}
$fetchData= fetch_data();
show_data($fetchData);
?>

<?php
function show_data($fetchData){
 echo '<table id="table1" class="display" border="1">
 <thead>
        <tr>
            <th> <input type="checkbox" id="selectAll"/></th>
            <th>ID</th>
            <th>საქონელი</th>
            <th>კოდი</th>
            <th>მყიდველი</th>
            <th>თარიღი</th>
            <th>ოპერაციის კომენტარი</th>
            <th>ერთეულის ფასი</th>
            <th>ვალუტა</th>
            <th>თანხა</th> 
        </tr>
 </thead>';
 if(count($fetchData)>0){
      $sn=1;
      foreach($fetchData as $data){ 

  echo "
  <tbody>
  <tr>
          <td><input type='checkbox' name='check-tab1' class='form-control'></td>
          <td>".$sn."</td>
          <td>".$data['saqoneli']."</td>
          <td>".$data['nomeri']."</td>
          <td>".$data['myidveli']."</td>
          <td>".$data['tarigi']."</td>
          <td>".$data['operaciis_komentari']."</td>
          <td>".$data['erteulis_fasi']."</td>
          <td>".$data['valuta']."</td>
          <td>".$data['tanxa']."</td>
   </tr>";
   
  $sn++; 
     }
     }else{
     
     echo "<tr>
        <td colspan='7'>No Data Found</td>
       </tr>"; 
     }
    echo "
    </tbody>   
    </table>";
    }
    
?>
<html>
    <br>
    <div class="tab tab-btn">
                <button onclick="tab1_To_tab2();">>>>>></button>
                
            </div>
    <h1>--------------------------მეორე ცხრილი-----------------------</h1>
<table  id="table2" name="tablename" class="secondtable" border="1">
    <thead>
        <tr>
            <th>ID</th>
            <th>საქონელი</th>
            <th>კოდი</th>
            <th>მყიდველი</th>
            <th>თარიღი</th>
            <th>ოპერაციის კომენტარი</th>
            <th>ერთეულის ფასი</th>
            <th>ვალუტა</th>
            <th>თანხა</th> 
        </tr>
    </thead> 
    <tfoot>
        <tr>
            <th colspan='8' style='text-align:right'>Total:</th>
            <th></th>
        </tr>
</tfoot>   
</table> 
</html>
<script>


function sumOfColumns(){
var totalQuantity = 0;
var totalPrice = 0;
$(".someClass").each(function(){
    totalQuantity += parseInt($(this).html());
    $(".someTotalClass").html(totalQuantity);
});

$(".classPrice").each(function(){
    totalPrice += parseInt($(this).html());
    $(".someTotalPrice").html(totalPrice);
});
}

//ჯამი მთავარი ცხრილისთვის
/*
$(function() {
var TotalValue = 0;
$("tr #loop").each(function(index,value){
  currentRow = parseFloat($(this).text());
  TotalValue += currentRow
});
document.getElementById('total').innerHTML = TotalValue;
});
*/

function tab1_To_tab2()
            {
            var table1 = document.getElementById("table1"),
                    table2 = document.getElementById("table2"),
                    checkboxes = document.getElementsByName("check-tab1");
            console.log("Val1 = " + checkboxes.length);
                 for(var i = 0; i < checkboxes.length; i++)
                     if(checkboxes[i].checked)
                        {
                            // create new row and cells
                            var newRow = table2.insertRow(table2.length),
                                cell1 = newRow.insertCell(0),
                                cell2 = newRow.insertCell(1),
                                cell3 = newRow.insertCell(2),
                                cell4 = newRow.insertCell(3);
                                cell5 = newRow.insertCell(4);
                                cell6 = newRow.insertCell(5);
                                cell7 = newRow.insertCell(6);
                                cell8 = newRow.insertCell(7);
                                cell9 = newRow.insertCell(8);                   
                            // add values to the cells
                            cell1.innerHTML = table1.rows[i+1].cells[1].innerHTML;
                            cell2.innerHTML = table1.rows[i+1].cells[2].innerHTML;
                            cell3.innerHTML = table1.rows[i+1].cells[3].innerHTML;
                            cell4.innerHTML = table1.rows[i+1].cells[4].innerHTML;
                            cell5.innerHTML = table1.rows[i+1].cells[5].innerHTML;
                            cell6.innerHTML = table1.rows[i+1].cells[6].innerHTML;
                            cell7.innerHTML = table1.rows[i+1].cells[7].innerHTML;
                            cell8.innerHTML = table1.rows[i+1].cells[8].innerHTML;
                            cell9.innerHTML = table1.rows[i+1].cells[9].innerHTML;
                        
                            // remove the transfered rows from the first table [table1]
                            var index = table1.rows[i+1].rowIndex;
                            table1.deleteRow(index);
                            // we have deleted some rows so the checkboxes.length have changed
                            // so we have to decrement the value of i
                            i--;
                           console.log(checkboxes.length);     
                        }     
            }
            
$('#selectAll').click(function(event) {
    $('table tr:visible :checkbox').prop('checked', this.checked)
     });
    // Live Search
$(document).ready(function(){  
    $('#search').keyup(function(){  
        search_table($(this).val());  
        });  
        function search_table(value){  
            $('#table1 tbody tr').each(function(){  
                var found = 'false';  
                    $(this).each(function(){  
                        if($(this).text().toLowerCase().indexOf(value.toLowerCase()) >= 0)  
                        {  
                            found = 'true';  
                        }  
                    });  
                    if(found == 'true')  
                    {  
                        $(this).show();  
                    }  
                    else  
                    {  
                        $(this).hide();  
                    }  
            });  
        }  
    });


    $(document).ready(function() {
    $('#table2').DataTable( {
        "footerCallback": function ( row, data, start, end, display ) {
            var api = this.api(), data;
 
            // Remove the formatting to get integer data for summation
            var intVal = function ( i ) {
                return typeof i === 'string' ?
                    i.replace(/[\$,]/g, '')*1 :
                    typeof i === 'number' ?
                        i : 0;
            };
 
            // Total over all pages
            total = api
                .column( 8 )
                .data()
                .reduce( function (a, b) {
                    return intVal(a) + intVal(b);
                }, 0 );
 
            // Total over this page
            pageTotal = api
                .column( 8, { page: 'current'} )
                .data()
                .reduce( function (a, b) {
                    return intVal(a) + intVal(b);
                }, 0 );
 
            // Update footer
            $( api.column( 8 ).footer() ).html(
                '$'+pageTotal +' ( $'+ total +' total)'
            );
        }
    } );
} );

</script>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<style>
table{
    display: block;
    width: 100%;
    height: 300px;
    overflow-y: auto;
    clear: both;
    border-collapse: separate;
    border-spacing: 0;
    font-size: 12px;
    justify-content: center;
    align-items: center;
    }
.secondtable{
    border-collapse:collapse;
    margin:auto;
    padding:40;
    width: calc(100% - 10px);
    overflow-y: auto;
    clear: both;
    border-collapse: separate;
    border-spacing: 0;
    font-size: 12px;
    justify-content: center;
    align-items: center;
    }
    
table th {
    position: sticky;
    top: 0;
    background: #B0BED9;
    }
table, td, th {  
      border: 1px solid #ddd;
      text-align: left;}
.table-data{
        position: relative;
      left:50px;
      top:50px;}
th, td {
      padding: 10px;
    }
    </style>
<body>


<link href='DataTables/datatables.min.css' rel='stylesheet' type='text/css'>

<link rel="stylesheet" type="text/css" href="jquery-ui.min.css">

<!-- jQuery Library -->
<script src="jquery-3.4.1.min.js"></script>

<script type="text/javascript" src="jquery-ui.min.js"></script>

<!-- Datatable JS -->
<script src="DataTables/datatables.min.js"></script>

<div id="table-container"></div>



      
<script type="text/javascript" src="ajax-script.js"></script>


</body>
</html>

Any ideas and help appreciated.

  • welcome to stackoverflow – you may find out the solution yourself if you boil it down to a minimalistic scenario! What I see when looking over the code are at least two places where your code is not downright wrong, but not really right-and-proper either! .. you place a starting TBODY tag before every row, this shouldn't really matter to a proper browser, but you should fix that. Then in your event-hook into footerCallback you pass "data" as argument and then define it as a variable too .. again, not wrong, but has code-smell (for me). – flowtron Dec 02 '20 at 08:14
  • @flowtron Thanks for replay. Same code for footerCallback works fine for. other tables, but here it does nothing... – Vakhtang Zubiashvili VakhoZuba Dec 02 '20 at 09:02
  • without data to play around with we only have the code to go on – you could make it shorter & prettier by using arrays in tab1_to_tab2() where you repeat code just with different indexes in each line .. text-book use-case for lists/arrays. .. "does nothing" .. not even any output on the console? Then maybe do that for debugging: put some console.log() debug output into the processing .. at the start of the callback output all the arguments via console.log or console.dir and inside the reduce calls too .. to make sure your code is seeing the data your code is expecting. – flowtron Dec 02 '20 at 09:46
  • @flowtron did you see PIC i attached? I have not reied what you suddest yet, but i think i will get same result. Problem is in adding, the table is already generated and after transfering data from first table rows goes after that – Vakhtang Zubiashvili VakhoZuba Dec 02 '20 at 10:10
  • If you want to transfer data to a second DataTables table (as opposed to transferring data to a plain HTML table) then you need to use the DataTables API. Specifically, you need to use `row.add()` or `rows.add()`. See [here](https://datatables.net/examples/api/add_row) for documentation. Your current approach is to add data to the HTML table - but DataTables will not know anything about this data (and therefore will not be able to sum it, or even re-display it after a table action). – andrewJames Dec 02 '20 at 13:01
  • @andrewjames Thank you, you help me a lot <3 – Vakhtang Zubiashvili VakhoZuba Dec 07 '20 at 11:07

0 Answers0