Javascript trick

Beatnik on 2003-12-23T23:46:46

Here's one that has been puzzling me for quite some time. It took me a while to find an easy and working example online so I'm posting this in case someone else needs this as well.

It concerns a parent and a child window. The parent window is your main browser window, the child window is a basic pop-up (the good kind). The example below is used in a situation where the space on the page is too small for all form fields. I moved the more advanced fields to the advanced pop-up but I want to make sure all fields are saved when pressing the save button on the parent window.

This is the main form. It contains a hidden field for each of the fields in the pop-up window. Through Javascript, you read and set those values.

<form action="foo.pl" method="post">
<input type="button" value="Advanced" onclick="window.open('advanced.html','AdvancedWindow','width=600,height=200,scrollbars=yes'); return false;">
<input type="hidden" name="extrafield" value="foo">
<input type="submit">
</form>


The following bit is the HTML for the child window (in this case in advanced.html)

<head>
<script type="text/javascript">
function storeValues(newform) {
self.opener.document.forms[0].extrafield.value = newform.extrafield.value;
self.close();
}

function loadValues() {
var newform = document.forms[0];
newform.extrafield.value = self.opener.document.forms[0].extrafield.value;
}
</script>
</head>
<body onload="loadValues();">
<form name="newform">
<input type="button" value="Save" onclick="storeValues(document.newform)">
Field : <input name="extrafield" type="text">
</form>


Hope this helps anyone :D