【问题标题】:How to select and check changes of DropDownList in GridView?如何在 GridView 中选择和检查 DropDownList 的变化?
【发布时间】:2013-03-19 07:36:52
【问题描述】:

我在 GridiView 中有一个 ASP.NET GridView 控件和 DropDownList 控件,如下所示:

<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 中选择 DropDownList,然后检查更改?

请指教。 提前谢谢你。

【问题讨论】:

    标签: javascript jquery asp.net gridview


    【解决方案1】:

    使用class selector为下拉列表和bind事件分配css class

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

    【讨论】:

    • 在你的 html 中,class 属性应该在 asp:DropDownList 元素中。而且我认为CssClass服务器端属性更好。
    • 啊,很好,但是需要将该类分配给下拉列表,而不是您所显示的 gridview。纠正它,你有我的投票。 :)
    【解决方案2】:

    你正在尝试这样使用有点困难

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

    但请确保您没有任何控制 ID,例如 DropDownList1

    【讨论】:

    • +1 这也可以,虽然我觉得类选择器可能更快...
    【解决方案3】:

    尝试与.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.

    【讨论】:

    • 因为会有很多下拉列表,所以我认为这不会起作用。
    猜你喜欢
    • 2017-04-19
    • 2011-06-05
    • 1970-01-01
    • 1970-01-01
    • 2016-11-21
    • 1970-01-01
    • 2019-09-19
    • 1970-01-01
    • 2023-03-30
    相关资源
    最近更新 更多