2013-03-19 35 views
1

我有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,然後檢查更改?

請指教。 先進的謝謝。

回答

4

指定一個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

0

嘗試用.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

1

當您嘗試是有點難以利用這樣

$("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

相關問題