1
votes

I have a ASP.NET GridView control and DropDownList control inside the GridiView as below:

<asp:GridView ID="GridView1" runat="server">
    <Columns>
        <asp:TemplateField>
            <ItemTemplate>
                <asp:DropDownList ID="DropDownList1" runat="server">
                </asp:DropDownList>
            </ItemTemplate>
        </asp:TemplateField>
     </Columns>
</asp:GridView>

I wanted to use jQuery/ JavaScript to get DropDownList element and detect the item change as below:

$(function() {
    $("#<%= DropDownList1.ClientID %>").change(function() {
        if ($("#<%= DropDownList1.ClientID %>").find('option:selected').text() == "1") {
            alert('1');
        } else {
            alert('2');
        }
    });
});

My question is, how can I select the DropDownList inside GridView, and then check for the changes?

Please advise. Thank you in advanced.

3

3 Answers

4
votes

Assign a css class to dropdownlist and bind event with class, using class selector

Html

<asp:GridView ID="GridView1" runat="server" >
    <Columns>
        <asp:TemplateField>
            <ItemTemplate>
                <asp:DropDownList ID="DropDownList1" runat="server" CssClass="ddlclass">
                </asp:DropDownList>
            </ItemTemplate>
        </asp:TemplateField>
     </Columns>
</asp:GridView>

Javascript

$(function() {
    $(".ddlclass").change(function() {
        if ($(this).find('option:selected').text() == "1") {
            alert('1');
        } else {
            alert('2');
        }
    });
});
1
votes

As you are trying is bit difficult use like this

 $("input[id*=DropDownList1]")

$(function() {
     $("input[id*=DropDownList1]").change(function() {
        if ($(this).find('option:selected').text() == "1") {
            alert('1');
        } else {
            alert('2');
        }
    });
});

But make sure you don't have any control id like DropDownList1

0
votes

Try using with .find():

$(function() {
   $("#GridView1").find("[id^='DropDownList']").change(function() {
      if ($('option:selected',this).text() == "1") {
          alert('1');
      } else {
          alert('2');
      }
   });
});

I don't work in .net environment so its a total guess, might be useful.

Note: The above line only work if your ids are starting with DropDownList.