[Vuejs]-How to SUM cells from DataTables when checked?

0👍

You can use a footer in your datatable. Just make it initially invisible and add some boilerplate to show some results.

<table id="dt_container">
    <tfoot style="display: none;">
        <tr>
            <th>Total:</th>
            <th><input id="total" type="text" name="total" value="" readonly></th>
        </tr>
    </tfoot>
</table>

Next, in the javascript init the DataTable but add some callbacks

// Adds the values and updates the readonly input.
function updateTotal(){
    $('input#total').val($('input.selected:checked').toArray().reduce(function(last, current){
        return last + parseInt($(current).attr('data-value'));
    }, 0);
}
// init the total value and bind updateTotal function to the change event on the checkboxes.
function dt_init(){
    updateTotal();

    $('.selected').off('change').on('change', function(e){
        updateTotal();
    });
}

var dt = $('#dt_container').DataTable({
    // Add the checkboxes and set the values in a data-* attribute for later
    rowCallback: function(row, data){
        let value = parseInt($('td:eq(4)', row).html().substring(3))
        // $('td:eq(4)', row).html()  : 'R$ 12975.00'
        // 'R$ 12975.00'.substring(3) : '12975.00'
        // parseInt('12975.00')       : 12975
        $('td:eq(0)', row).html(`<input class="selected" type="checkbox" data-value=${value}>`)
    },
    // If you need to redraw your table (sort, search, page), then you need to redo some things, that's why dt_init is called upon every time.
    initComplete: function(settings, json, param){
        // show the footer after the DataTable is done
        $(dt.table().footer()).css('display', '');
        dt_init();
    },
    drawCallback: function(settings){
        dt_init();
    }
});

Leave a comment