如何选择和检查GridView中DropDownList的更改?

如何选择和检查GridView中DropDownList的更改?

问题描述:

我有GridiView如下内ASP.NET GridView控件和DropDownList控件:如何选择和检查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,然后检查更改?

请指教。 先进的谢谢。

指定一个css class为DropDownList和bind事件带班,使用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'); 
     } 
    }); 
}); 
+0

任何控件的ID在你的HTML,class属性应该是在ASP :DropDownList元素。我认为CssClass服务器端属性更好。 – 2013-03-19 07:42:26

+0

啊,非常好,但是需要将类分配到下拉列表中,而不是像显示的那样分配给gridview。纠正它,你有我的投票。 :) – Icarus 2013-03-19 07:42:33

+0

谢谢你们,更新了我的答案。 – Adil 2013-03-19 07:44:46

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

+0

因为会有很多下拉列表,所以我认为这不会起作用。 – 2013-03-19 07:44:47

当您尝试是有点难以利用这样

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

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

但要确保你没有像DropDownList1

+0

+1这也将工作,虽然我觉得类选择器可能会更快...... – Icarus 2013-03-19 07:46:19