在使用javascript和jquery获取错误时计算gridview单元格的总和

时间:2011-05-22 09:10:33

标签: javascript asp.net

我正在使用 java script jquery 计算GridView个单元格的总数。但是,编译时我总是遇到这个错误。

  

名称'total'在。中不存在   当前背景

内部GridView代码:

<asp:TemplateField HeaderText="Header 1">
    <ItemTemplate>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    </ItemTemplate>            
    <FooterTemplate>
        <asp:Label ID="lblTotal" runat="server" Text="Total" Font-Bold="true">
        </asp:Label>
    </FooterTemplate>            
</asp:TemplateField>
<asp:TemplateField HeaderText="Header 2" >
    <ItemTemplate>
        <asp:TextBox ID="TextBox2" runat="server" class="calculate" 
           onchange="calculate()"></asp:TextBox>
    </ItemTemplate>            
    <FooterTemplate>
        <asp:TextBox ID="total" runat="server"></asp:TextBox>
    </FooterTemplate>  

javascript jquery 代码:

<script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.min.js" 
  type="text/javascript">
  <script language="javascript" type="text/javascript">
    function calculate()
     {
        var txtTotal = 0.00;
        //var passed = false;
        //var id = 0;

        $(".calculate").each(function (index, value) {
            var val = value.value;
            val = val.replace(",", ".");
            txtTotal = MathRound(parseFloat(txtTotal) + parseFloat(val));
        });
        document.getElementById("<%=total.ClientID %>").value = txtTotal.toFixed(2);
    }

    function MathRound(number) {
        return Math.round(number * 100) / 100;
    }

</script>

如何帮助解决这个问题。

2 个答案:

答案 0 :(得分:0)

您无法轻松访问GridView等模板控件内的控件。创建一个变量来保存total.ClientID,以便jQuery可以抓住它。

在你的aspx中:

var totalClientID = TotalClientID;

在codebehind中:

void GridView1_RowDataBound(Object sender, GridViewRowEventArgs e)
{
   if(e.Row.RowType == DataControlRowType.Footer)
   {
       TotalClientID = ((TextBox)e.Row.FindControl("total")).ClientID;
   }
}

答案 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`