Can't find form on returned HTML
I have a main page consisting of a link and a div with id 'containerDiv'. When you press the link it loads some HTML from another page using Ajax into this div.
The HTML that is returned contains a form. When the form is submitted, I wish to stay on the same page and display the resulting content in the div.
Please see a picture showing what I wish to accomplish by clicking this link.
The script on the main page:
<script type="text/javascript">
$(document).ready(function () {
$("a").click(function () {
$('#containerDiv').load(this.href + ' #contentDiv', function () {
alert($('#page2Form').id);
$('#page2Form').submit(function () {
$.post(
pageName,
this.serialize(),
function (data) {
if (data.success)
alert('done');
else
alert('error');
$('#containerDiv').html(data);
}
);
return false;
});开发者_运维技巧
});
return false;
});
});
</script>
The relevant HTML on the main page:
<a id="link1" href="page1.aspx">Page 1</a>
<br />
<div id='console' style="border: 2px solid red; width: 1000px">
when the link is clicked this content is replaced with new html.
</div>
The relevant HTML on the content page:
<div id="contentDiv">
<form id="page2Form" runat="server">
<div>
<h1>
Page 2</h1>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="submit" OnClick="Submit_OnClick" />
</div>
</form>
</div>
The problem is that I can't find the form 'page2Form' on the returned HTML.
Alert ($('#page2Form'). id); returns 'undefined'
Perhaps it has something to do with that element is not loaded in the DOM.
A few things here, jQuery objects won't have a .id
property, you want the id
of the first element in the matched set, like this:
alert($('#page2Form')[0].id);
//or without jquery:
alert(document.getElementById('page2Form').id);
Also, make sure you're looking for it after the $('#containerDiv').html(data);
call, so it's added to the DOM. If you're looking for it before it's added, then use the returning data
as the context to look in, like this:
alert($('#page2Form', data)[0].id);
精彩评论