Sum of DropDownList Selected Values Inside GridView Using jQuery

This article demonstrates the use of jQuery with ASP.Net to calculate the sum of DropDownList selected values and display the total.

Task Description

We have a GridView Control containing the DropDownlist in it's TemplateField Column (ItemTemplate). Each DropDownList has some selected integer value. The sum of these selected values should display below DropDownList and should also be updated as the user changes any DropDownList selected value.

How to do it

This is done using jQuery. A class "items" is added to DropDownList. This class is further used by jQuery to find the DropDownList on the client-side. On the "document ready" and "DropDownList's change" events a method "CalculateTotal" is called, that performs the main task. Here is the code.

Code Behind

using System;

using System.Collections.Generic;

public partial class _Default : System.Web.UI.Page

{

    protected void Page_Load(object sender, EventArgs e)

    {

        List<Number> list = new List<Number>();

        list.Add(new Number("1"));

        list.Add(new Number("2"));

        list.Add(new Number("3"));

        list.Add(new Number("4"));

        GridView1.DataSource = list;

        GridView1.DataBind();

    }

    public class Number

    {

        public string Num { get; set; }

        public Number(string str)

        {

            this.Num = str;

        }

    }

}


ASPX
 

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">

<Columns>

<asp:TemplateField HeaderText="Serial Number">

<ItemTemplate>

<%# ((Number)Container.DataItem).Num %>

</ItemTemplate>

</asp:TemplateField>

<asp:TemplateField HeaderText="Values">

<ItemTemplate>

<asp:DropDownList ID="DropDownList1" runat="server"ClientIDMode="Static" CssClass="items">

<asp:ListItem>1</asp:ListItem>

<asp:ListItem>2</asp:ListItem>

<asp:ListItem>3</asp:ListItem>

<asp:ListItem>4</asp:ListItem>

</asp:DropDownList>

</ItemTemplate>

</asp:TemplateField>

</Columns>

</asp:GridView>

<br />

Total : <asp:Label ID="LabelTotal" runat="server" ClientIDMode="Static"></asp:Label>

 

<script>

    $(document).ready(function () {

        CalculateTotal();

        $('.items').change(function () { CalculateTotal(); });

    });

    function CalculateTotal() {

        var val = 0;

        $('.items').each(function () {

            val = val + parseFloat($(this).find('option:selected').val());

        });

        $('#LabelTotal').text(val);

        val = 0;

    }

</script>

Output

DropDownList selected Values