Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

How Javascript passes values between two forms


May 30, 2021 Article blog



As we all know, the window.open() function can be used to open a new window, so how do you pass values to the parent form in a child form, in fact, you can get a reference to the parent form through window.opener.

As we created the new form FatherPage .htm:

XML-Code:

<script type="text/javascript">
function OpenChildWindow(){ 
window.open('ChildPage.htm'); }
</script>
<input type="text" id="txtInput" />
<input type="button" value="OpenChild" onclick="OpenChildWindow()" />

The elements in the parent form can then be accessed through window.opener in the ChildPage .htm:


XML-Code:

<script type="text/javascript">
function SetValue(){ 
window.opener.document.getElementById('txtInput').value =document.getElementById('txtInput').value; 
window.close();}
</script>
<input type="text" id="txtInput" />
<input type="button" value="SetFather" onclick="SetValue()" />

In fact, while opening a sub-form, we can also assign values to the elements of the sub-form, because the window.open function also returns a reference to a sub-form, so FatherPage .htm can be modified to:

XML-Code:

<script type="text/javascript">
function OpenChildWindow(){ 
var child = window.open('ChildPage.htm'); 
child.document.getElementById('txtInput').value =document.getElementById('txtInput').value; }
</script>
<input type="text" id="txtInput"/>
<input type="button" value="OpenChild" onclick="OpenChildWindow()" />

By determining whether a reference to a sub-form is empty, we can also control that it can only open one sub-form:

XML-Code:

<script type="text/javascript">
var childfunction OpenChildWindow(){ 
if(!child) child = window.open('ChildPage.htm'); 
child.document.getElementById('txtInput').value =document.getElementById('txtInput').value; }
</script>
<input type="text" id="txtInput" />
<input type="button" value="OpenChild" onclick="OpenChildWindow()" />

That's not enough, you must also empty the child variable of the parent form when you close the child form, or you won't be able to reopen the child form after you open it:

XML-Code:

<body onunload="Unload()">
<script type="text/javascript">
function SetValue(){ 
window.opener.document.getElementById('txtInput').value =document.getElementById('txtInput').value; 
window.close();}
function Unload(){ 
window.opener.child=null;}
</script>
<input type="text" id="txtInput" />
<input type="button" value="SetFather" onclick="SetValue()" />
</body>