Pass variable to datatables footercallback function for caluclation

Pass variable to datatables footercallback function for caluclation

jigar311982jigar311982 Posts: 70Questions: 31Answers: 0

Hello,

How can I pass the additional variable value in footercallback?

I have below code for dropdown selection,

    $('#tax_id').change(function () {
        var tax = $('#tax_id').val();
        return tax;
    });

Above function is returning tax value as per selection,
Now i want to pass this tax value to datatable footer calculations,

            footerCallback: function ( row, data, start, end, display ) {
                var api = this.api(), data;
        
                var intVal = function ( i ) {
                        return typeof i === 'string' ?
                                i.replace(/[\$,]/g, '')*1 :
                                typeof i === 'number' ?
                                        i : 0;
                };

                var itemsTotal = api.column(1).data().reduce(function(a, b) {
                    return intVal(a) + intVal(b);
                }, 0);

                var priceTotal = api.column(5).data().reduce(function(a, b) {
                    return intVal(a) + intVal(b);
                }, 0);

                var taxTotal = priceTotal - (priceTotal * ( 100/ (100 + tax) )) ;
                // Update footer in second row, second cell .eq is JS propery
                $('tr:eq(0) th:eq(2)', api.table().footer()).html(taxTotal.toFixed(2));
                $('tr:eq(1) th:eq(1)', api.table().footer()).html(itemsTotal);
                $('tr:eq(2) th:eq(1)', api.table().footer()).html(priceTotal.toFixed(2));
                
                //Update total in main header
                $("#totalValue span").text(priceTotal.toFixed(2));
                $("#totalTax span").text(taxTotal.toFixed(2));
            },

How can i do that?

Thanks,

This question has an accepted answers - jump to answer

Answers

  • kthorngrenkthorngren Posts: 21,336Questions: 26Answers: 4,951

    Either have the footerCallback function fetch the value from the input $('#tax_id').val() or make the tax variable global, for example:

    var tax;
    $('#tax_id').change(function () {
        tax = $('#tax_id').val();
        return tax;
    });
    

    Kevin

  • jigar311982jigar311982 Posts: 70Questions: 31Answers: 0

    Hi Kevin,
    Yes, but my tax is dropdown selection, so based on the change in tax value footer calculations need to be done based on the value from the selection.
    So that means every time change in the selection of tax, footerCallback should run,
    How can I do?

  • kthorngrenkthorngren Posts: 21,336Questions: 26Answers: 4,951
    edited December 2020 Answer ✓

    Call the draw() API, like this:

    $('#tax_id').change(function () {
        var tax = $('#tax_id').val();
        $('#myTableID').DataTable().draw();
        return tax;
    });
    
This discussion has been closed.