How to Calculate the Sum of GridView Columns Using JavaScript?
I have a GridView with three COlumns Which will be like this:
ID Sign Amount
------ -------- ---------
1 + 1000
2 - 500
3 - 750
So the Sum of the Column "Amount" Should be "-250". Consider the Column "Sign" also with the Amount. Here is my GridView's Source Code:
<Columns>
<asp:BoundField DataField="ID" HeaderTe开发者_JAVA技巧xt="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>
So far, I have written One JavaScript, But It Only Calculate the Sum of Amount. I dont know how to calculate the Sum based on the Sign values. Below is the JavaScript I have written:
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);
}
So Please Make Changes to this Javascript.
can you try the below code?
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);
}
<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`
精彩评论