Javascript – Get a value from a pop up window

The following example shows u how to open a pop up window and get a value from it by using javascript. You can use it as the starting point of creating a more complex feature.

index.html

<script type="text/javascript">
	// open a pop up window
	function openPopUpWindow(targetField){
		var w = window.open('popup.html','_blank','width=400,height=400,scrollbars=1');
		// pass the targetField to the pop up window
		w.targetField = targetField;
		w.focus();
	}

	// this function is called by the pop up window
	function setSearchResult(targetField, returnValue){
		targetField.value = returnValue;
		window.focus();
	}
</script>
<form name="thisForm">
	<table>
		<tr>
			<td>Put bob here: </td>
			<td><input type="text" name="textbox1" /></td>
			<td><a href="#" onclick="openPopUpWindow(document.thisForm.textbox1)">Search</a></td>
		</tr>
		<tr>
			<td>Put Alice here: </td>
			<td><input type="text" name="textbox2" /></td>
			<td><a href="#" onclick="openPopUpWindow(document.thisForm.textbox2)">Search</a></td>
		</tr>
	</table>
</form>

popup.html

<script type="text/javascript">
	// return the value to the parent window
	function returnYourChoice(choice){
		opener.setSearchResult(targetField, choice);
		window.close();
	}
</script>
<form name="thisForm">
	<table>
		<tr>
			<td><span style="color:blue" onclick="returnYourChoice('Bob')">Halo, I am Bob =)</span></td>
		</tr>
		<tr>
			<td><span style="color:blue" onclick="returnYourChoice('Alice')">Hi, I am Alice ^^</span></td>
		</tr>
		<tr>
			<td><span style="color:blue" onclick="returnYourChoice('Kit')">I won't tell u my name.</span></td>
		</tr>
	</table>
</form

Advertisements

7 thoughts on “Javascript – Get a value from a pop up window”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.