Aaron Aaron - 4 years ago 216
Javascript Question

JavaScript/HTML5 Take URL from form and open it in a new Window iframe

I'm currently trying to write a JavaScript function that will take a URL from a form once the user has entered it into a textbox and clicked a button to open in a new window that contains an iframe. Here's what I currently have:

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Untitled Document</title>
<style type="text/css">
label {
display:block;
}
</style>
<script type="text/javascript">

function goTo() {
var url = document.forms[0].url.value;
myWindow = window.open('', '', 'width=800,height=800');
myWindow.document.write("<iframe src='url'></iframe>");
myWindow.focus();
return false;
}

</script>
</head>
<body>
<form action="" method="get" onsubmit="return goTo()">
<label for="url">Enter the URL:
<input type="text" name="url" id="url">
<input type="submit" value="Submit">
</form>
</body>
</html>


The main problem I'm currently having is determining how to pass the url variable into the document.write() method. It will work fine when I try a typical source URL in the iframe, but naturually that defeats the purpose since I want to use a user passed-in value. Any assistance is welcomed, I have no vanity-of-authorship so if I'm fundamentally doing things wrong, I'm ok with that -- seeking you pros to let me know.

Answer Source

The url variable is part of a string in your example. Try this instead. Also, make sure that it's a valid URL.

myWindow.document.write("<iframe src='"+ url +"'></iframe>");

I might also add that writing an iframe in the new window is a bit redundant. you should just do

myWindow = window.open(url, "", "width=800,height=800");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download