问题
Using the below code I am trying to write some validation code on change event of dropdown "ddlAction".
I have tried few ways e.g.
$(".ddlAction").change(function () {$("#grdApproval").find("[id^='ddlAction']").change(function () {$("input[id*=ddlAction]").change(function ()$("input[value*=ddlAction]").change(function () {- --> Works only if I am on gridview's page one.
C# Code:
<asp:TemplateField HeaderText="ACTION" ItemStyle-Width="10%">
<ItemTemplate>
<asp:DropDownList ID="ddlAction" CssClass="ddlAction" runat="server" BorderStyle="Solid" Width="150px" SkinID="GridEdit" ValidationGroup="Compensation" Enabled="true"/>
</ItemTemplate>
</asp:TemplateField>
JQuery :
$(function () {
$(".ddlAction").change(function () {
//$("#grdApproval").find("[id*='ddlAction']").change(function () {
//$("input[id*=ddlAction]").change(function () {
//$("input[value*=ddlAction]").change(function () {
//do something;
});
});
Page source :
<select name="ctl00$MainContent$grdApproval$ctl03$ddlAction" id="MainContent_grdApproval_ddlAction_1" class="ddlAction" style="color:Black;background-color:#FFFF99;border-style:Solid;font-family:Verdana;font-size:9pt;width:150px;">
<option value="97" title="-----------Select-----------">-----------Select-----------</option>
<option value="FS" title="Finalize-Submit">Finalize-Submit</option>
<option value="NMR" title="Needs More Research">Needs More Research</option>
回答1:
This:
$(".ddlAction").on('change', function () {
})
should work. it will attach on change event to every .ddlAction drop down on the page , not just table
You are not showing gridview id, I consider it to be '#grdApproval'
So your code better be changed to:
$('#grdApproval').on('change','.ddlAction', function() {
})
this way it will use event delegation.
It might not work pages other than first in case you are using callbacks for gridview, or wrapped gridview in UpdatePanel
In both of this cases you need to re-set handler after async-postback
UPDATE: In case you have update panel you need to do the following:
// lets say you have function that you call to init your page:
function myInit() {
$('#grdApproval').on('change','.ddlAction', function() {
})
}
// and you calling it on page load
$(document).ready(myInit)
// add the following line, to run the same code on pageLoaded
// for async postback driven by UpdatePanel
Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(myInit);
回答2:
Below code worked and issue fixed by re-attaching event after async-postback
JQuery:
function pageLoad(sender, args) {
$(document).ready(function () {
$(".ddlAction").change(function () {
var HFStatusChangedId = this.id.replace("ddlAction", "HFStatusChanged");
if (this.selectedIndex !== "97") {
document.getElementById(HFStatusChangedId).value = "Y";
}
});
});
}
来源:https://stackoverflow.com/questions/24000345/jquery-class-selector-is-not-working-in-asp-net-gridview