Forum Moderators: open

Message Too Old, No Replies

How to pass a variable between two windows by using "window.open"?

         

guarriman

11:03 am on Mar 11, 2008 (gmt 0)

10+ Year Member



Hi.

From the parent page, I want to create a form within a window created by
--------
<FORM>
<INPUT type="button" value="New Window" onClick="window.open('http://www.foo.com/form.html','newwindow','width=300,height=200')">
</FORM>
--------

And within 'http://www.foo.com/form.html' I want to create a variable which I want to pass to parent page. Is it possible?

Thank you very much.

Fotiman

3:14 pm on Mar 11, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



First, you should make your form accessible for those who don't have JavaScript enabled. In other words, if JavaScript is disabled, then your <form> needs an "action" attribute. Also, your example above uses "obtrusive" JavaScript, meaning you've mixed your content (HTML markup) with your behaviors (JavaScript) by using inline event handlers.

Below is my example which uses unobtrusive JavaScript and progressive enhancement. It works whether JavaScript is enabled or not. In my example, my pure HTML form has a submit button, and I then use JavaScript to replace that submit button with a regular button that will open the new window. Note also I'm using the Yahoo UI Library for it's event handling utility (makes it easier to attach event handlers in an unobtrusive way).


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset:utf-8">
<title></title>
</head>
<body>
<form action="http://www.example.com/form.html">
<div>
<input type="text" name="foo" value="123">
<input type="text" name="bar" value="abc">
<input type="submit" id="submitBtn" value="Submit">
</div>
</form>
<script type="text/javascript" src="http://yui.yahooapis.com/2.5.0/build/yahoo-dom-event/yahoo-dom-event.js"></script>
<script type="text/javascript">
YAHOO.util.Event.onDOMReady(function() {
var E = YAHOO.util.Event;
var submitBtn, regularBtn;
// Replace the submit button with a regular button
submitBtn = document.getElementById('submitBtn');
regularBtn = document.createElement('input');
regularBtn.type = 'button';
regularBtn.value = submitBtn.value + ' to New Window';
submitBtn.parentNode.replaceChild(regularBtn, submitBtn);
// Attach onclick handling for button
E.on(regularBtn, 'click', function(e) {
E.stopEvent(e);
var url = this.form.action + '?';
var i, el, len = this.form.elements.length;
for (i = 0; i < len; i++) {
// If you have form inputs other than type 'text', you may need
// to do some special handling here
el = this.form.elements[i];
if (el.name && el.name.length > 0) {
url += el.name + '=' + escape(el.value) + '&';
}
}
window.open(url);
});
});
</script>
</body>
</html>

[edited by: Fotiman at 3:16 pm (utc) on Mar. 11, 2008]