kyle_13
kyle_13

Reputation: 1233

Update iframe src attribute dynamically with JavaScript

I'm trying to update an iframe on a page using JavaScript, but it's not working. This example seems pretty straightforward, but the page is not loading the iframe with the new page once I click the button. I'm doing this all locally.

<html>
    <body>
    <script>
    function changeIframeSrc() {
        document.getElementById('myFrame').src = "test2.html";
    }
    </script>
    <form>
    <button onclick="changeIframeSrc()">Click here</button>
    <iframe id="myFrame" src="test1.html"></iframe>
    </form>
    </body>
    </html>

Upvotes: 2

Views: 2411

Answers (2)

Nisse Engstr&#246;m
Nisse Engstr&#246;m

Reputation: 4752

The script does load the new <iframe>. The problem is that the <form> is also submitted (if the browser supports implicit form submission) which then reloads the page with the original <iframe>.

One simple solution is to remove the <form> element. Without a <form> element, there can be no form submission:

<!--form-->
 <button onclick="changeIframeSrc()">Click here</button>
 <iframe id="myFrame" src="test1.html"></iframe>
<!--/form-->

Another is to prevent the default action of the <button> by returning false from the onclick handler:

<form>
 <button onclick="changeIframeSrc(); return false;">Click here</button>
 <iframe id="myFrame" src="test1.html"></iframe>
</form>

However, there is a problem with these solutions. If the browser doesn't execute the script, or the script fails in some unanticipated way, the user is left with a dead button. Ideally, the button should submit the form in a useful way when the script doesn't run. Eg.:

<form>
 <button name=frame value=2 onclick="changeIframeSrc(); return false;">Click here</button>
 <iframe id="myFrame" src="test1.html"></iframe>
</form>

The add some server-side code that outputs the form, but with src="test2.html" as the default <iframe> source if the page is requested with the form data frame=2.

Upvotes: 2

Joseph Didion
Joseph Didion

Reputation: 142

Just remove The form tags

<html>
<body>
<script>
function changeIframeSrc() {
    document.getElementById('myFrame').src = "test2.html";
}
</script>
<button onclick="changeIframeSrc()">Click here</button>
<iframe id="myFrame" src="test1.html"></iframe>
</body>
</html>

Upvotes: 2

Related Questions