Aggregation in Kendo Grid specifically for the current page

I'm currently facing an issue with the Kendo Grid aggregate function that I'm struggling to resolve.

Within the grid, I have multiple rows with numerical values. My goal is to display the total sum of these rows at the bottom of the grid.

The functionality is already implemented and can be seen in action in this fiddle:

http://jsfiddle.net/0Ly94e49/

$(document).ready(function () {
$("#grid").kendoGrid({
    dataSource: {
        type: "odata",
        transport: {
            read: "http://demos.kendoui.com/service/Northwind.svc/Products"
        },
        pageSize: 7,

        aggregate: [{
            field: "ProductName",
            aggregate: "count"
        }, {
            field: "UnitPrice",
            aggregate: "sum"
        }, {
            field: "UnitsOnOrder",
            aggregate: "sum"
        }, {
            field: "UnitsInStock",
            aggregate: "min"
        }, {
            field: "UnitsInStock",
            aggregate: "max"
        }]
    },
    sortable: true,
    scrollable: false,
    pageable: true,
    columns: [{
        field: "ProductName",
        title: "Product Name",
        footerTemplate: "Total Count: #=count#",
    }, {
        field: "UnitPrice",
        title: "Unit Price"
    }, {
        field: "UnitsOnOrder",
        title: "Units On Order",
        footerTemplate: "Sum: #=sum#",
    }]
});
});

The issue I'm facing, as shown in the fiddle, is that the sum calculation includes all rows across all pages. I'm looking to calculate the sum only for the rows on the current page.

Does anyone have any suggestions on how to modify the fiddle to achieve this?

The project is developed in Angular, if that information is relevant.

Thank you in advance.

Answer №1

My accomplishment in this particular scenario. I have compiled an aggregate:

dataSource: {
                        data: dataOfTable,
                        aggregate: [
                            {field: "field1", aggregate: "sum"},
                            {field: "field2", aggregate: "sum"},
                            {field: "field3", aggregate: "sum"}
                        ],
                        pageSize: 20
                    },

FooterTemplate for the column:

    {
 field: "field1",
 title: 'Field1',
 footerTemplate: "#=getCurrentField1()#"    
 }

for field2, field3, and others:

{
 field: "field2",
 title: 'Field2',
 footerTemplate: "#=currentField2#"    
 }

And the function getCurrentField1:

//  aggregates data on the current page
            var currentField1 = 0;
            var currentField2 = 0;
            var currentField3 = 0;

            function getCurrentField1() {

                var displayedData = $("#grid").data().kendoGrid.dataSource.view()

                var resField1 = 0;
                var resField2 = 0;
                var resField3 = 0;

                for (var i = 0; i <= displayedData.length; i++) {
                    if (displayedData[i] != undefined) {
                        resField1 += displayedData[i].field1;
                        resField2 += displayedData[i].field2;
                        resField3 += displayedData[i].field3;
                    }
                }

                currentField1 = resField1;
                currentField2 = resField2;
                currentField3 = resField3;
                return currentPayAmount;
            }

Due to dataBound pagination malfunctioning, the current data in footerTemplates were inaccurate as the binding was done after the value was set. Therefore, I added a function to the first column to calculate all current values and set them correctly.

Answer №2

At the conclusion of my process, I calculated the sum of the current page as follows:

 $scope.calculatePageTotal = function () {
           var pageNum = $scope.grid.dataSource.page();
           var pageSize = $scope.grid.dataSource.pageSize();
           var firstIndex = pageSize * (pageNum - 1);
           var lastIndex = firstIndex + pageSize - 1;
           var totalAmount = 0;
           var totalDistance = 0;
           for (var index = firstIndex; index <= lastIndex; index++) {
               if (allEntries[index] != undefined) {
                   totalAmount += allEntries[index].AmountToReimburse;
                   totalDistance += allEntries[index].Distance;
               }

           }
           $scope.currentPageAmountTotal = totalAmount;
           $scope.currentPageDistanceTotal = totalDistance;

 }

I assigned the received rows from the server to allEntries in the schema section of the data source

Schema {
       Data: function(data){
             allEntries = data;
       }
}

Subsequently, I invoked calculatePageTotal in the data bound section of the data source

dataBound: function () {
           $scope.calculatePageTotal();
}

Finally, I linked the currentPageSum value to the footerTemplate of the relevant field

field: "Distance",
title: "Distance",
footerTemplate: "Page: {{currentPageDistanceTotal}}, total: #= sum # "

Answer №3

Enable serverPaging for optimal performance.

 pageSize: 7,
 serverPaging : true,
 aggregate: [{
                field: "ProductName",
                aggregate: "count"
            }, {
                field: "UnitPrice",
                aggregate: "sum"
            }, {
                field: "UnitsOnOrder",
                aggregate: "sum"
            }, {
                field: "UnitsInStock",
                aggregate: "min"
            }, {
                field: "UnitsInStock",
                aggregate: "max"
            }]

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Connect to a node.js server from a different network

Looking to set up a basic live chat using node.js, socket.io, and express. Managed to get it working on my local network, but wondering if there's a way for someone from another internet connection to connect without me needing to pay for server space ...

``Why is it that the JavaScript code is unable to find the maximum or minimum sum? Let's

function calculateMinMaxSums(arr) { // Custom code implementation let max = Math.max(...arr); let min = Math.min(...arr); let minsum = 0; let maxsum = 0; for (let x in arr) { if (arr[x] != max) { minsum += arr[x]; }; if (arr[x ...

Removing an item from JSON data using Node.js and Express

Currently, I am attempting to remove an entry from json data. In order to view the data, I utilize the following: app.route('/data/:id') .get((req:Request, res: Response) => { let id = req.params.id; res.status(200).send(projects ...

Exploring client-server relationships within the Express framework

Is there a way to transfer an object to JavaScript on the client side? I previously asked this question and received an answer, but because I was unable to check it on my computer, I accepted the response. You can view the details here: Client receive jso ...

Modify the text of a button using JavaScript without referencing a specific div class

THE ISSUE I'm facing a challenge in changing the text of a button on my website. The <div> I need to target doesn't have a specific class, making it difficult for me to make this edit. While I have some basic understanding of JavaScript, ...

Modifying the href attribute of links within various occurrences of an element using jQuery based on its content

Here is an illustration of a recurring element on a webpage <td class=" market all"> <a href="linktosomesite?param=123" target="_blank">123</a> </td> Similar elements change the parameter, resulting in links like: <td clas ...

The JavaScript array on its second usage had a length of '0', yet it still contained objects within it

About the Task: This task involves working with two arrays: arrNumber, which is a number array, and arrString, which is a string array. The goal is to create a list of objects using the values from arrNumber, where the object keys are numbers or characte ...

Testing the $watch function in AngularJS using Jasmine

I am relatively new to AngularJS and recently delving into unit testing with Jasmine. I am tasked with writing a test for the following code: $scope.$watch( function () { return alertService.getAlert(); }, function (newVal, oldVal) { if (typeof ne ...

Display when moving up and conceal when moving down

Is there a way to make the div appear when scrolling up and down on the page? I'm new to jquery and could use some assistance, please. ...

Data has not been submitted to the MongoDB database

I attempted to save form data in my mongodb database (mongodb compass). However, after submitting the form, I checked the database and found that it was empty. When I clicked the sign-up button, it only displayed curly brackets. Main file - App.js co ...

Is it possible for me to load a window following a click

I developed a customized Modal Box that functions similar to the browser's "alert()". When using the traditional alert(), it halts the rendering and executions of the underlying webpage. I am seeking methods to achieve this same behavior: preventing ...

Guide to adding sound effects to your Vue 3 app using the Composition API

I'm having trouble setting up a basic button click feature in Vue 3 Composition API to play a sound effect. In my setup function, I have imported an mp3 sound effect from the assets folder and passed it into a ref method with an HTMLAudioElement type, ...

Refresh Material-Ui's Selection Options

Is there a way to properly re-render the <option> </option> inside a Material UI select component? My goal is to transfer data from one object array to another using the Material UI select feature. {transferData.map(data => ( <option ...

Angularfire not updating $scope value

I've encountered an issue with my code. The $scope value doesn't update after using $createUserWithEmailAndPassword. However, when I use alert($scope.message), the alert appears. What am I doing wrong? I have all the latest files from firebase a ...

The code execution continues as Sweetalert does not wait for the user's response

swal({title: "Are you sure?", text: "Your form will be submitted", confirmButtonText: "Ok", showConfirmButton:true, showCancelButton: true, cancelButtonText: "No", type:"warning", closeOnConfirm: false, closeOnCancel: false }, ...

Display corresponding div elements upon clicking an HTML select option

Is there a way to make a div visible when a corresponding select option is clicked, while hiding others? My JavaScript skills are lacking in this area. CSS #aaa, #bbb, #ccc { display:none; } The HTML (I'm using the same id name for option and d ...

Invisible Thinglink image revealed upon resizing browser

I am currently repurposing a pre-existing theme that has a drop-down menu showcasing an image. I am attempting to integrate a Thinglink into the content section of this drop-down, but unfortunately, the image does not appear until I adjust the size of the ...

Having challenges retrieving information from MySQL in AngularJS

As a beginner in angularJS, I am trying to display all customers from MySQL. Here is the code I have written in the controller and service: app.controller('CustomersController', function ($scope, customersService, $http) { init(); function ini ...

send parameter when clicking a link rather than using a hashtag

One interesting feature on my website is a menu link with the attribute title=.roc. When this link is clicked, I want to extract this attribute and click on an element with the same attribute on the destination page. Let's consider a scenario where I ...

Having issues sending multiple variables to PHP through Ajax

Trying to pass three variables through the URL using Ajax - one constant and two from a date picker. The constant passes fine, but the date variables are only passing as their names. Here's the code for the date pickers: <tr> ...