如何使用JavaScript计算GridView列的总和?

时间:2011-06-09 05:37:43

标签: javascript asp.net user-controls

我有一个带有三个COl的GridView,如下所示:

 ID                  Sign                Amount
------              --------             ---------
 1                    +                   1000
 2                    -                    500
 3                    -                    750

因此“金额”栏的总和应为“-250”。考虑列“符号”也与金额。 这是我的GridView的源代码:

 <Columns> 
  <asp:BoundField DataField="ID" HeaderText="ID"/>
       <asp:TemplateField HeaderText="Sign" >
        <ItemTemplate>
 <asp:TextBox ID="txtgvSign" runat="server" Text='<%# Bind("Sign") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
 <asp:TemplateField HeaderText="Amount">
  <ItemTemplate>
 <asp:TextBox ID="txtAmount" runat="server" Text='<%# Bind("Amount") %>'></asp:TextBox>  
</ItemTemplate>
</asp:TemplateField>
</Columns> 

到目前为止,我已经编写了一个JavaScript,但它只计算了金额的总和。我不知道如何根据Sign值计算Sum。以下是我写的JavaScript:

  function CalculateTax(fixedtotal)
  {
    var taxgrid = document.getElementById('<%=gvAttribute.ClientID %>');
    var taxip = taxgrid.getElementsByTagName('input');
    var taxamount = 0*1;

    for(i = 0; i < taxip.length; i++)
    {
        var tax = taxip[i].value;            
        taxamount = parseFloat(taxamount) + parseFloat(tax);
    }
    return parseFloat(fixedtotal) + parseFloat(taxamount);
  }

所以请对此Javascript进行更改。

2 个答案:

答案 0 :(得分:2)

你可以试试下面的代码吗?

  function CalculateTax(fixedtotal)
  {
    var taxgrid = document.getElementById('<%=gvAttribute.ClientID %>');
    var taxip = taxgrid.getElementsByTagName('input');
    var taxamount = 0*1;

    for(i = 0; i < taxip.length; i+= 2)
    {
        var sign = taxip[i].value;            
        var tax = taxip[i+1].value; 
        taxamount = parseFloat(taxamount) + (sign =='+' ? 1 : -1)* parseFloat(tax);
    }
    return parseFloat(fixedtotal) + parseFloat(taxamount);
  }

答案 1 :(得分:0)

<script language="javascript" type="text/javascript">
    function Calculate() {

        var grid = document.getElementById("<%=grid.ClientID%>");
        var sum = 0;
        for (var i = 1; i < grid.rows.length; i++) {
            var Cell = grid.rows[i].getElementsByTagName("input");
            if (!Cell[4].value) {sum += 0; } else { sum += parseFloat(Cell[0].value);}
        }

        alert(sum);        
    }

</script> 



<asp:TemplateField HeaderText="Current payment" >
<ItemTemplate>
    <asp:TextBox ID="txtvalue" runat="server" Width="70px" BorderStyle="None" onkeyup="Calculate();" ></asp:TextBox>
</ItemTemplate>
<ItemStyle Width="120px" />
</asp:TemplateField>`enter code here`