Bootstrap Table Data Formatter Footer On Multiple Columns

by Greg Esguerra

HTML

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.2.0/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.18.0/bootstrap-table.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.18.0/bootstrap-table.min.js"></script>
<table id="tblDemo" class="table-condensed table-striped" data-show-footer="true">
	<thead>
		<tr>
			<th data-field="id">ID</th>
			<th data-field="name">Name</th>
			<th data-field="value" data-footer-formatter="SumFormatter">Value 1</th>
			<th data-field="value2" data-footer-formatter="SumFormatter">Value 2</th>
		</tr>
	</thead>
</table>

JavaScript

$(function () {
    var $table = $('#tblDemo');
    var mydata = 
    [
        {
            "id": 1,
            "name": "test1",
            "value": "15",
			"value2": "6"
        },
        {
            "id": 2,
            "name": "test2",
            "value": "3",
			"value2": "2"
        },
        {
            "id": 3,
            "name": "test3",
            "value": "2",
			"value2": "5"
        },
        {
            "id": 4,
            "name": "test4",
            "value": "6",
			"value2": "1"
        },
        {
            "id": 5,
            "name": "test5",
            "value": "5",
			      "value2": "20"
        },
        {
            "id": 6,
            "name": "test6",
            "value": "5",
					  "value2": "1"
        },
        {
            "id": 7,
            "name": "test7",
            "value": "22",
						"value2": "18"
        },
        {
            "id": 8,
            "name": "test8",
            "value": "32",
						"value2": "9"
        },
        {
            "id": 9,
            "name": "test9",
            "value": "3",
						"value2": "5"
        },
        {
            "id": 10,
            "name": "test10",
            "value": "4",
						"value2": "13"
        }
    ];

    $('#tblDemo').bootstrapTable({
        data: mydata
    });
});

function SumFormatter (items) {
  var total = 0;

	if (this.field === "value") {
		  items.forEach(function (item) {
		   total += parseFloat(item.value);
	   });
	}
	else {            
	  items.forEach(function (item) {
		total += parseFloat(item.value2);
	   });
	}

	return parseFloat(total) === 0 ? "0" : total;
};