Ayman
Ayman

Reputation: 109

Get sum of gridview textboxes values and show total in label using javascript

I have in my application a grid-view in which a number of textboxes as template field, which can be incremented.When i enter some value in first textbox the sum of all textbox should be shown in Label. I have tried to use the below code but it didn't work.

JavaScript

<script type="text/javascript">
    function calculate() {
        var txtTotal = 0.00;

        $(".calculate").each(function (index, value) {
            var val = value.value;
            val = val.replace(",", ".");
            txtTotal = MathRound(parseFloat(txtTotal) + parseFloat(val));
        });

        document.getElementById("<%= lbltotal.ClientID %>").value = txtTotal.toFixed(2);
    }

    function MathRound(number) {
        var result = Math.round(number * 100) / 100;
        return result;
    }
</script>

GridView

<asp:GridView ID="GridView1" runat="server" ShowFooter="true" AutoGenerateColumns="false">
    <Columns>
        <asp:BoundField DataField="RowNumber" HeaderText="Row Number" />
        <asp:BoundField DataField="Description" HeaderText="Item Description" />
        <asp:TemplateField HeaderText="Amount">
            <ItemTemplate>
                <asp:TextBox ID="txtamount" onkeyup="calculate();" CssClass="calculate" runat="server" Text=""></asp:TextBox>
            </ItemTemplate>

        </asp:TemplateField>
    </Columns>
</asp:GridView>

label

<asp:Label ID="lbltotal" runat="server" Text="" ForeColor="Green"></asp:Label>

Upvotes: 1

Views: 5807

Answers (1)

VDWWD
VDWWD

Reputation: 35564

Use this snippet. It adds an keyup listener to every TextBox in GridView1. Then it loops all the TextBoxes and adds the values and put the total in Label1

<script type="text/javascript">
    var total = 0;

    $(document).ready(function () {
        $('#<%= GridView1.ClientID %> input[type="text"]').keyup(function () {
            $('#<%= GridView1.ClientID %> input[type="text"]').each(function () {
                if ($(this).val() != "") {
                    total += parseFloat($(this).val());
                }
            });
            document.getElementById("<%= Label1.ClientID %>").innerHTML = total.toFixed(2);
        });
    });
</script>

Upvotes: 1

Related Questions