Donate

ASP.NET Trigger Onchange Event Of DropDownList Inside GridView Using jQuery

There was a question in a forum if how can we trigger an onchange event of a DropDownList control inside a GridView template field. This time using unobtrusive approach. So in order to understand a bit further, the GridView control when rendered to the browser becomes a table element while DropDownList becomes a Select control.
So, to trigger the event we need to traverse the GridView control then find the Select control and attach a change event. Here's a solution using jQuery.
HTML Markup:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
<asp:GridView ID="gvItem" runat="server" AutoGenerateColumns="False">
        <Columns>
            <asp:BoundField DataField="ID" HeaderText="ID" />
            <asp:BoundField DataField="ProductName" HeaderText="ProductName" />
            <asp:TemplateField HeaderText="Time Slot">
                <ItemTemplate> 
                    <asp:DropDownList ID="Time_Slot" runat ="server">
                        <asp:ListItem Selected="True" Value="0">Select...</asp:ListItem>
                        <asp:ListItem Value="1">8:00</asp:ListItem>
                        <asp:ListItem Value="2">9:00</asp:ListItem>
                        <asp:ListItem Value="3">10:00</asp:ListItem>
                        <asp:ListItem Value="4">11:00</asp:ListItem>
                        <asp:ListItem Value="5">12:00</asp:ListItem>
                        <asp:ListItem Value="6">1:00</asp:ListItem>
                        <asp:ListItem Value="7">2:00</asp:ListItem>
                        <asp:ListItem Value="8">3:00</asp:ListItem>
                        <asp:ListItem Value="9">4:00</asp:ListItem>
                    </asp:DropDownList> 
                </ItemTemplate> 
            </asp:TemplateField>
        </Columns>      
    </asp:GridView>

jQuery code:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
$(document).ready(function() {
    $("#<%=gvItem.ClientID%> tr").each(function(index) {
        if ($(this) != undefined) {
            var temp = $(this).find("select").change(function() {
                if ($(this).children(":selected").html().toString().indexOf("Select") == -1) {
                    alert("Selected order time: " + $(this).children(":selected").html());
                }
            });
        }
    });
});

Screenshot:
ASP.NET Trigger Onchange Event Of DropDownList Inside GridView Using jQuery

Comments

Donate

Popular Posts From This Blog

WPF CRUD Application Using DataGrid, MVVM Pattern, Entity Framework, And C#.NET

How To Insert Or Add Emojis In Microsoft Teams Status Message

Bootstrap Modal In ASP.NET MVC With CRUD Operations