如何在GridView中选择和检查下拉列表的更改

How to select and check changes of DropDownList in GridView?

本文关键字:下拉列表 检查 选择 GridView      更新时间:2023-09-26

我有一个ASP。. NET GridView控件和GridView中的下拉列表控件,如下所示:

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

我想使用jQuery/JavaScript来获取DropDownList元素并检测项目的变化,如下所示:

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

我的问题是,我如何在GridView中选择下拉列表,然后检查更改?

请建议。

使用class选择器为classbind的下拉列表和事件指定class

<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');
        }
    });
});

当你尝试有点困难时,像这样使用

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

但要确保没有任何控件id,如DropDownList1

尝试使用.find():

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

我不工作在.net环境,所以这是一个完全的猜测,可能是有用的。

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