简体   繁体   中英

How to get a sum of column of GridView using JavaScript

I'm trying to access to the column named Time of a gridview and calculate Sum of whole column using JavaScript.

I have something like this:

在此处输入图片说明

So in Report total I want to get number 5, since it is only entry right now.

This is a definition of a gridview:

<div class="total">

    <asp:GridView ID="ReportGrid" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDS" Height="68px" Width="813px" AllowPaging="True">
        <Columns>
            <asp:BoundField DataField="Date" HeaderText="Date" SortExpression="Date" DataFormatString="{0:MM/dd/yy}" />
            <asp:BoundField DataField="Name" HeaderText="Team Member Name" SortExpression="Name" />
            <asp:BoundField DataField="ProjectName" HeaderText="Projects" SortExpression="ProjectName" />
            <asp:BoundField DataField="Description" HeaderText="Description" SortExpression="Description" />
            <asp:BoundField DataField="Time" HeaderText="Time" SortExpression="Time" />
        </Columns>
    </asp:GridView>
    <br />
    <br />
    <span>Report total: <em>
        <asp:Label runat="server" ID="totalHours" Text="0"></asp:Label></em></span>
</div>

Can anyone help me with javaScript code for this problem or share with me some related links, cause all I've found on the internet wasn't similar to this, and I guess this is simple thing to do when you know how to use JS.

NaN value for sum during debugging:

在此处输入图片说明

Add a css class to your fields

    <asp:BoundField DataField="Time" HeaderText="Time"> 
      <ItemStyle CssClass="yourclass"></ItemStyle> 
     </asp:BoundField> 

and use the following code

 var fields= document.getElementsByClassName('yourclass');
    var sum = 0;
    for (var i = 0; i < fields.length; ++i) {
        var item = fields[i];  
         sum += parseInt(item.innerHTML);
    }

and then assign that sum to your total label

$("#<%= totalHours.ClientID %>").text(sum);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM