【问题标题】:Javascript/jquery calculate totals in gridviewJavascript / jquery在gridview中计算总数
【发布时间】:2012-10-08 09:13:24
【问题描述】:

我有一个带有产品详细信息的网格视图和一个我添加的数量文本框——它没有连接到任何数据库。 我希望它为每一行显示成本(价格*数量)和所有行的总成本(在下面的标签中)。 我有一些问题。 1.它在数量文本框中输入一个0,所以我需要一直将数量更新为1,然后计算。

我也知道,也许这可以在 C# 中的 rowdataboundevent 中做得更好,不胜感激。

请帮助我了解问题所在。 这是代码:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.js"></script>
    <script type="text/javascript">

$(function () {
    $("[id*=lblquantity]").val("0");
    });
$("[id*=lblquantity]").live("change", function () {
        if (isNaN(parseInt($(this).val()))) {
            $(this).val('0');
        } else {
            $(this).val(parseInt($(this).val()).toString());
        }
    });
    $("[id*=lblquantity]").live("keyup", function () {
        if (!jQuery.trim($(this).val()) == '') {
            if (!isNaN(parseFloat($(this).val()))) {
                var row = $(this).closest("tr");
                $("[id*=lblTotal]", row).html(parseFloat($(".price", row).html()) * parseFloat($(this).val()));
            }
        } else {
            $(this).val('');
        }
        var grandTotal = 0;
        $("[id*=lblTotal]").each(function () {
            grandTotal = grandTotal + parseFloat($(this).html());
        });
        $("[id*=lblGrandTotal]").html(grandTotal.toString());
        $("[id*=hfGrandTotal]").val(grandTotal.toString())
    });
    </script>

这是 ASP.net 中 gridview 的代码。

 <asp:HiddenField ID="hfGrandTotal" runat="server"  />
    <asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False" 
        EnableViewState="False" onrowdatabound="GridView2_RowDataBound">
        <Columns>
        <asp:BoundField DataField="Price" HeaderText="Price" ItemStyle-CssClass="price" >

<ItemStyle CssClass="price"></ItemStyle>
            </asp:BoundField>

                         <asp:TemplateField HeaderText="ProductID">
                <ItemTemplate>
                    <asp:Label ID="lblID" runat="server" Text='<%# Eval("ProductID") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
             <asp:TemplateField HeaderText="ProductName">
                <ItemTemplate>
                    <asp:Label ID="lblName" runat="server" Text='<%# Eval("ProductName") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>

             <asp:TemplateField HeaderText="Summary">
                <ItemTemplate>
                    <asp:Label ID="lblSum" runat="server" Text='<%# Eval("Summary") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
             <asp:TemplateField HeaderText="picPath">
                <ItemTemplate>
                    <asp:Label ID="lblPic" runat="server" Text='<%# Eval("picPath") %>' ></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>

            <asp:TemplateField HeaderText = "quantity">
            <ItemTemplate>
                <asp:TextBox ID="lblquantity" runat="server"  ></asp:TextBox>

            </ItemTemplate>
        </asp:TemplateField>

        <asp:TemplateField HeaderText = "Total">
            <ItemTemplate>
                <asp:Label ID="lblTotal" runat="server" ></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>



        </Columns>
    </asp:GridView>

感谢

【问题讨论】:

    标签: c# javascript jquery asp.net gridview


    【解决方案1】:

    进行这些更改

    步骤 1。将价格设为asp:TemplateField 并像这样向lblTotal 添加一个类。数量也应该是您所写的标记中的文本框吗?

    <asp:TemplateField HeaderText="Price">
        <ItemTemplate>
             <asp:Label ID="lblPrice" runat="server" CssClass="rowprice"></asp:Label>
        </ItemTemplate>
    </asp:TemplateField>
    <asp:TemplateField HeaderText="Quantity">
        <ItemTemplate>
             <asp:TextBox ID="txtQuantity" runat="server" CssClass="rowqty" Text="1">
             </asp:TextBox>
        </ItemTemplate>
    </asp:TemplateField>
    <asp:TemplateField HeaderText="Total">
        <ItemTemplate>
             <asp:Label ID="lblTotal" runat="server" CssClass="rowtotal"></asp:Label>
        </ItemTemplate>
    </asp:TemplateField>
    

    步骤 2。下载此numeric plugin 并将其写入 DOMReady

    $(document).ready(function() {
        $(".rowqty").numeric({
            decimal: false,
            negative: false
        });
    });​
    

    这是为了让数量文本框只接受正整数。

    第 3 步。

    protected void GridView2_RowDataBound(Object sender, GridViewRowEventArgs e)
    {
        if(e.Row.RowType == DataControlRowType.DataRow)
        {
             var priceLabel =  e.Row.FindControl("lblPrice") as Label;
             var quantityTextBox =  e.Row.FindControl("txtQuantity") as TextBox;
             var totalLabel =  e.Row.FindControl("lblPrice") as Label;
             var onKeyUpScript = String.Format(
                                      "javascript:CalculateRowTotal('#{0}', '#{1}', '#{2}');",
                                      quantityTextBox.ClientID,
                                      priceLabel.ClientID,
                                      totalLabel.ClientID);
             quantityTextBox.Attributes.Add("onkeyup", onKeyUpScript);
        }
    }
    

    第 3 步。添加asp:HiddenFieldasp:LabelClientIDMode="Static"

    <asp:HiddenField ID="hfGrandTotal" runat="server"></asp:HiddenField>
    Grand Total: <asp:Label ID="lblGrandTotal" runat="server"></asp:Label>
    

    第四步。在页面上添加javascript函数

    function CalculateRowTotal(qty_id, price_id, total_id) {
        var row_quantity = $(qty_id);
        var row_price = $(price_id);
        var row_total = $(total_id);
        var qty = parseInt($.trim($(this).val()), 10);
        if (isNaN(qty) || qty === 0) {
            qty = 1;
            row_quantity.val("1");
        }
        var totalAmount = parseFloat(row_price.html()) * qty;
        row_total.html(totalAmount);
        var grandTotal = 0;
        $(".rowtotal").each(function() {
            grandTotal += parseFloat($(this).html());
        });
        $("#hfGrandTotal").val(grandTotal);
        $("#lblGrandTotal").html(grandTotal);
    }​
    

    希望这会有所帮助。

    【讨论】:

    • 哇,你真的知道。我只是一个初学者,所以这些东西对我来说太重要了。我需要更简单的东西来申请。我不知道什么是 DOM。
    • DOM 是文档对象模型。简而言之,它是您的 html 本身,而 DOMReady 是 $(document).ready(function(){});
    • 这行得通吗?我遇到了同样的问题,在尝试了这段代码之后,keyup 永远不会触发。
    【解决方案2】:

    我不会在 JS 中这样做,因为这是客户端加载 + 更慢。

    按照您在 RowDataBound 中的说明填写。你的将在 GridView2_RowDataBound 中。
    只需找到控件并将其转换为正确的控件并填充文本即可。

    ((Label)e.Row.FindControl("lblTotal")).Text = (price * quantity);
    

    您的 dataItem 中可能存储了价格和数量。
    我认为您还必须将其转换为字符串,因为 .Text 需要字符串。
    你可以使用

    (price * quantity).ToString() 
    

    Convert.ToString(price * quantity);
    

    【讨论】:

    • 感谢您的回答。如果网格视图中有多行,我该怎么做?并且数量可以由用户更改,所以我需要添加一个“计算”按钮?!数量是网格视图内的文本框,价格取自会话中的数据表。
    • 您可以添加 id 或按类别。像值1,值2。使用 jQuery,您可以访问它们 jQuery(".value1") 或 jQuery("#value1")。您必须使用循环来绑定某些功能,例如单击或类似的功能。您可以查看 jQuery Each 函数。每种方法有 2 种,它们正在处理不同的元素。 jQuery.each 和 jQuery(".value1").each
    • 哇,谢谢。只是为了理解,我将 jquery 复制到我的 aspx 页面中。我还需要做什么吗?我如何替换 var price = 1.25;来自gridview的文本框的详细信息?
    • 你可以从后面的代码中添加属性函数。获取您的控件并将其添加为属性 ((HtmlControl)e.Item.FindControl("price")).Attributes.Add(String.format("price{0}", e.Item.DataItemIndex), "2") ;类似的东西。此示例来自中继器,因此在您的情况下,您将使用 e.Row 而不是 e.Item。然后从前端你可以在同一个循环中使用 jQuery 读取它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-26
    • 2016-03-07
    • 1970-01-01
    相关资源
    最近更新 更多