Accessing elements on the parent page of an iFrame

How do you cause events to fire on the parent page of an iFrame’d page?
Take this page structure:

Page1.htm
–DIV id=”Form1Container” (display:block)
—-iFrame name=”iFrame1″
—–Page2.asp
——Form id=Form1

–DIV id=”Form2Container” (display:none)
—Form id=”Form2″

In this example, there are 2 forms on Page1.htm.

Form1 is on an iFramed page: Page2.asp, and is visible when the page loads.

The second form, Form2 is outside the iFrame, on Page1.htm but is hidden.

When the user completes Form1 and clicks the Submit button, the iFrame should disappear, and Form2 becomes visible.

So what we want to have happen is:


Page1.htm
--DIV id="Form1Container" (display:none)
----iFrame name="iFrame1"
-----Page2.asp
------Form id=Form1

--DIV id="Form2Container" (display:block)
---Form id="Form2"

To make this happen, the onSubmit event on Page2.asp must fire a script that changes the style of #Form2Container on Page1.htm.

In the frame tree, Page1.htm is considered the “Parent” page of Page2.asp, so the path from Form1 to #Form2Container is:

parent.document.getElementById('Form2Container')...

So to hide Form1Container and show Form2Container at the same time, the script would look like:

<FORM name="Form1" method="post" action="somepage.asp" onsubmit="parent.document.getElementById('Form1Container').style.display = 'none'; parent.document.getElementById('Form2Container').style.display = 'block';"&rt;

or better:

(in head area)
function swapDivs(){
parent.document.getElementById('Form1Container').style.display = 'none'; 
parent.document.getElementById('Form2Container').style.display = 'block';
}


(in form tag)

<FORM name="Form1" method="post" action="somepage.asp" onsubmit="swapDivs();"&rt; 

Links to references on the subject of addressing elements in and around iFrames:

submit a page present in IFrame

Example of iFrame’d form

External HTML > Hidden Iframe > Div ?