Home Articles FAQs XREF Games Software Instant Books About Feedback Search Site-Map
irt.org logo

Q786 How can I open a child window when a form field submit button is first clicked, but switch focus to the child window on subsequent clicks?

irt.org | Knowledge Base | JavaScript | Window | Q786 [ previous next ]

Q786 How can I open a child window when a form field submit button is first clicked, but switch focus to the child window on subsequent clicks?

I would do it by using the TARGET attribute in conjunction with a window.open:

<script language="JavaScript"><!--
function myOpenWindow() {
    myWindowHandle = window.open('http://www.irt.org','myWindowName','width=400,height=400');
}
//--></script>

<form action="http://www.irt.org" target="myWindowName" onSubmit="myOpenWindow()">
<input type="text">
<input type="submit">
</form>

It works because the onSubmit event handler is triggered when the form is submitted - the myOpenWindow() function creates a pop-up window named myWindowName (note the third parameter of the window objects open() method). The onSubmit event handler then returns control back to the form which then targets the result into the already named and opened window myWindowName.

You may get one of two possible timing problems:

  • The window is not opened before the form attempts to target it
  • The window is opened and the page loaded, and then the form reloads it - causing a double load of the pop-up window

To avoid this you might like to try the following version instead:

<script language="JavaScript"><!--
buttonClicked=false;
function myOpenWindow() {
    myWindowHandle = window.open('about:blank','myWindowName','width=400,height=400');
}
//--></script>

<form name="myForm" action="http://www.irt.org" target="myWindowName" onSubmit="if (!buttonClicked) return false">
<input type="text">
<input type="button" onClick="myOpenWindow(); buttonClicked=true; setTimeout('document.myForm.submit()',500)" value="Open and submit">
</form>

Provide feedback ...
AddThis Social Bookmark Button

Provide feedback ... AddThis Social Bookmark Button


Last Updated: 30th March 2008. Maintained by: Martin Webb and Michel Plungjan
irt.org liability, trademark, document use, privacy statement and software licensing rules apply.
Copyright © 1996-2008 irt.org, All Rights Reserved.