【问题标题】:How to SUM cells from DataTables when checked?检查时如何对 DataTables 中的单元格求和?
【发布时间】:2019-07-26 17:26:43
【问题描述】:

我想在检查时对单元格中的值求和。喜欢:

我在 DataTables 网站上找到了方法,但它并不完全符合我的需要。 这张表上会有很多数据,当复选框被选中时,我想对它们的值求和,将总和保存在一个变量上以传递给控制器​​。

P.S.:我忘了说我使用的是 VueJS。让我们看一些代码。

@section('scripts')
<script type="text/javascript"
    src="https://cdn.datatables.net/v/dt/jszip-2.5.0/dt-1.10.16/af-2.2.2/b-1.5.1/b-colvis-1.5.1/b-flash-1.5.1/b-html5-1.5.1/b-print-1.5.1/cr-1.4.1/fh-3.1.3/kt-2.3.2/rg-1.0.2/rr-1.2.3/sl-1.2.5/datatables.min.js">
</script>
<script type="text/javascript" src="{{ asset('js/moment-with-locales.min.js') }}"></script>
<script>
    var vue = new Vue({
    el: '#app',
    data: {
        isLoading: false,
        cliente: '{{ $contemplado->id }}',
        checked : false,
        nrocpfCnpj: "{!! $contemplado->cpfCnpj !!}",
        porte: '{!! $contemplado->porte !!}',
        natureza_juridica: '{!! $contemplado->natureza_juridica !!}',
        idERP: '{!! $contrato->idERP !!}',
        originalSegmento: '{!! $contrato->originalSegmento !!}',
        novoSegmento: '{!! $contrato->novoSegmento !!}',
        isLoading: false,
        grupo: '{!! $contrato->grupo !!}',
        cota: '{!! $contrato->cota !!}',
    },

    mounted() {

        const vm = this
        var tabela = $('#example').dataTable({
            "language": {
                'url': '//cdn.datatables.net/plug-ins/1.10.16/i18n/Portuguese-Brasil.json'
            },
            'scrollX': true,
            'scrollY': false,
            'autoWidth': true,
            responsive: true,
            processing: true,
            "ajax": {
                "url": "montaTabelaMultiCota",
                "data": {
                    "nrocpfCnpj": vm.nrocpfCnpj
                }
            },
            columns: [
                { data: null,
                    fnCreatedCell: function (nTd, sData, oData, iRow, iCol) {
                        $(nTd).html("<div class='form-check'><input class='form-check-input' type='checkbox' name='cota"+oData['NUMERO-COTA']+"' value='"+oData['VALOR-BEM']+"'></div>")
                    }
                },
                { data: 'CODIGO-GRUPO'},
                { data: 'NUMERO-COTA',
                    fnCreatedCell: function (nTd, sData, oData, iRow, iCol) {
                        $(nTd).html(oData['NUMERO-COTA'])
                    }
                },
                { data: 'DESCRICAO-BEM'},
                { data: 'VALOR-BEM',
                    fnCreatedCell: function (nTd, sData, oData, iRow, iCol) {
                        $(nTd).html("R$ "+oData['VALOR-BEM']+",00")
                    }
                    },
                { data: 'NUMERO-CONTRATO'},
                { data: 'DATA-CONTEMPLACAO',
                        fnCreatedCell: function (nTd, sData, oData, iRow, iCol) {
                        moment.locale('pt-br');
                        var data = oData['DATA-CONTEMPLACAO'];
                        let criado = moment(data, 'YYYYMMDD').fromNow();
                            $(nTd).html(criado);
                    }
                },
                { data: 'DATA-ENTREGA',
                        fnCreatedCell: function (nTd, sData, oData, iRow, iCol) {
                        moment.locale('pt-br');
                        var data = oData['DATA-ENTREGA'];
                        let criado = moment(data, 'YYYYMMDD').fromNow();
                            $(nTd).html(criado);
                    }
                }
            ]
        });
        // 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();
            }
        });
    },
});

</script>
@endsection

有什么帮助吗? 非常感谢!

【问题讨论】:

    标签: laravel vue.js datatables sum


    【解决方案1】:

    您可以在数据表中使用页脚。只需让它最初不可见并添加一些样板以显示一些结果。

    <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>
    

    接下来,在 javascript 中初始化 DataTable,但添加一些回调

    // 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();
        }
    });
    

    【讨论】:

    • 亲爱的@IGP,除了 $.('.selected) 的错字之外,您的脚本根本不起作用。我已经编辑了我的问题,添加了您的代码。我错过了什么?
    • 重读您更新的问题,恐怕我的代码是针对 JQuery 而不是 Vue。
    • 好的,我会尝试将其转换为 VueJS。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2015-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多