I have a slight issue where I can’t seem to select a User Control ID using jquery. The User Control is a message panel which appears when an action happens. So when the page loads this message panel isn’t part of the page. It is only when the user interacts with the page i.e. add an image that the message panel shows with a message.
Page controls
<asp:Panel ID="pan_cntrls" runat="server">
<asp:Button ID="btnAddNewImg" runat="server" Text="Add new image" OnClick="btnAddNewImg_Click"
Visible="true" />
<uc9:MessagePanel ID="messagepanel1" runat="server"></uc9:MessagePanel>
</asp:Panel>
Javascript
<script language="javascript" type="text/javascript">
$(document).ready(function () {
$("#PageContent_IMG1_messagepanel1_divMessageBox").click(function () {
alert("handler called");
});
});
What firebug shows
<div class="errorBox confirmation" id="PageContent_IMG1_messagepanel1_divMessageBox" style="height: 50px;">
I can select other IDs using jquery but not this one. I should also point out that I am using a modalpopupextender on the page. So when I submit data the page is doing postback. I tried using delegate because the ID is added to the DOM after page load but its not working.
Any ideas?
Thanks
Basically, the problem is that you’re adding the handler at
$(document).ready. The divs don’t exist yet, so this call does nothing.You need to attach the click handler after the div hits the page. There are a couple of ways you can achieve this:
1
Use
add_endRequest, so execute thedocument.readycode after async queries:or 2
Explicitly make an addHandler function and cause it using an injection from asp.net:
In JS:
In ASP.Net:
Use
RegisterStartupScriptto call the addHandler, passing theClientIDof the control that needs the handler adding. See here for info on RegisterStartupScript.The first of these options is less efficient than the second (as it will execute after all postbacks), but easier to implement.