Tuesday, March 31, 2009

Parent Child Relationship in Javascript



In this post i will show how to call parent window function from child window and how to pass value from child window to parent window.
Parent.aspx



<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Parent.aspx.cs" Inherits="Parent" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>

<script language="Javascript" type="text/javascript">
function CallAlert() {
alert("This is parent window's alert function.");
}
function ButtonClickByChild() {
alert("Click by child.");
}
var newwindow;
function poptastic(url) {
newwindow = window.open(url, 'name', 'height=400,width=700');
if (window.focus) {
newwindow.focus()
}
}

</script>

</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="btnParent" runat="server" OnClientClick="ButtonClickByChild();" Text="Parent Button Clicked By Child" />
<asp:TextBox ID="txtParent" runat="server"></asp:TextBox>
<a href="javascript:poptastic('Child.aspx');">Open Child Window</a>
</div>
</form>
</body>
</html>

Child.aspx


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Child.aspx.cs" Inherits="Child" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>

<script type="text/javascript">
//Method call parent window function
function ParentWindowFunction() {
window.opener.CallAlert();
return false;
}
//Method pass value from child to parent
function SetParentText() {
window.opener.document.getElementById("txtParent").value =
document.getElementById("txtChild").value;
window.opener.document.getElementById("btnParent").click();
//Call this function in real application
// window.close();
return false;

}
</script>

</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtChild" runat="server"></asp:TextBox>
</div>
<asp:Button ID="btnChild1" runat="server" Text="Pass Value To Parent" OnClientClick="return SetParentText();" />
<asp:Button ID="btnChild2" runat="server" Text="Call Parent Function" OnClientClick="ParentWindowFunction();" />
</form>
</body>
</html>

0 comments:

Your Ad Here