How to post form from a popup window to a parent window

I was working on a client website and he requested that the form fields on a pop-up window should be posted to the parent window and the process should continue in the parent window from there on.

I was thinking of a quick ready made solution to this problem and surprisingly there were not many after doing a search for it on Google. I thought “How hard could it be?” and wrote a few lines of JavaScript and the task was complete in 15 minutes. It was quite easy.

I created the form and the form fields on the parent page as seen below

<html>
<head></head>
<body>
<form name="frmPost">
<input type="hidden" name="txtFname"/>
<input type="hidden" name="txtLname"/>
</form>	
</body>
</html>

Then I wrote the JavaScript code on the pop-up window which would be actually posting the fields to the parent window.

<script type="text/javascript">
function post_it() {
opener.document.forms[0].action = document.forms['frmInfo'].action;
opener.document.forms[0].txtFname.value = document.forms['frmInfo'].txtFname.value;
opener.document.forms[0].txtLname.value = document.forms['frmInfo'].txtLname.value;
opener.document.forms[0].submit();
}
</script>

I called the above function from the pop-up window page and it started to work correctly by posting the fields to the parent window.

The opener keyword from above is a JavaScript object referring to the parent page from which the pop-up window was opened. The forms[0] refers to the first form on the parent page. The forms[‘frmInfo’] refers to the frmInfo form on the pop-up page. Please note that you can reference forms via their indices or names as you can see from the above example.

If you would like to close the pop-up window after posting the form then you can add one more line as follows

<script type="text/javascript">
function post_it() {
opener.document.forms[0].action = document.forms['frmInfo'].action;
opener.document.forms[0].txtFname.value = document.forms['frmInfo'].txtFname.value;
opener.document.forms[0].txtLname.value = document.forms['frmInfo'].txtLname.value;
opener.document.forms[0].submit();
window.close();
}
</script>

Hope the above helps.

Leave a Reply

Your email address will not be published. Required fields are marked *