数据表列总和错误添加字符串值列

时间:2017-03-29 15:55:52

标签: php jquery codeigniter datatables sum

我在codeigniter应用程序中使用了一个数据表来动态打印数据库值。我试图总结所有列,包括数值和字符串值。数值是正确的,但字符串列总和是奇怪的错误。总和仅适用于列的某些值。例如,它总计了10行中的8行。但数字和显示所有10行的总和。 我提供以下代码。 注意:我正在尝试使用headercallback()来打印列的总和。我为此使用了两个标题。

数据表HTML代码:

<table id="tabular" class="table table-striped table-bordered"   cellspacing="0" width="100%">
    <thead>
        <tr>
            <th>Company</th>
            <th>Status</th>
            <th>Created Date</th>
            <th>Total Contacts</th>
            <th>Total Versions</th>
            <th>Articles Assigned</th>
        </tr>
    </thead>


    <thead id="totals">    
        <tr>
            <th id="name">asdfasf</th>
            <th></th>
            <th></th>
            <th id="contact"></th>
            <th id="version"></th>
            <th id="article"></th>
        </tr>            
    </thead>

    <tbody>......(Rest of the code)

JS代码初始化给定HTML上的数据表

$(document).ready(function() {

    var oTable = $('#tabular').DataTable({
        // "stateSave": true,
        //  "order": [],
        "dom": '<"row search-padding" <"col-md-12 search-padding" <"col-md-6  search-padding pull-left" <"#inp">> <"col-md-6 search-padding" <"datatable-n  pull-right" l >> > >rt <"row" <"col-md-6"  i > <"col-md-6" p > >',
        "columns" : [
                    {"width": "25%" },
                    {"width": "18.7%" },
                    {"width": "18.7%" },
                    {"width": "14%" },
                    {"width": "10.7%" },
                    {"width": "18.7%" },
                    ],
                    "stashSave":true,
         "order": [],
         "processing": true, 
         "searching" : true,
         "orderCellsTop": true,
         "language": {
         "emptyTable": "No companies found for the selected range."
        },
   //code to sum up columns...

        "headerCallback": function () {
            var api = this.api(),
                columns = [0,3,4,5]; // Add columns here

            for (var i = 0; i < columns.length; i++) {

                $('#totals th').eq(columns[i]).html('Total: ' +  api.column(columns[i], {filter: 'applied'}).data().sum() + '<br>');    
            }
        }
} );

我使用了sum()api:

jQuery.fn.dataTable.Api.register( 'sum()', function ( ) {
return this.flatten().reduce( function ( a, b ) {
    if ( typeof a === 'string' ) {
        a = a.replace(/[^\d.-]/g, '') * 1;
    }
    if ( typeof b === 'string' ) {
        b = b.replace(/[^\d.-]/g, '') * 1;
    }

    return a + b;
}, 0 );
} );

我已经尝试了所有方法来获得正确的价值。我已经交叉检查了数据库查询,我得到了正确的数据。

希望我已经说清楚了。建议会有所帮助。感谢

0 个答案:

没有答案