Home >Web Front-end >JS Tutorial >How to Correctly Modify iFrame Source Using JavaScript?

How to Correctly Modify iFrame Source Using JavaScript?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-20 19:20:03536browse

How to Correctly Modify iFrame Source Using JavaScript?

Modifying iFrame Source Using JavaScript

When faced with the task of dynamically updating an iframe's src attribute in response to user interaction, one may encounter unexpected errors. Let's investigate a typical example where the desired functionality is to change the src attribute of an iframe labeled "calendar" upon clicking a radio button.

Here's the code in question:

<code class="html">function go(loc) {
  document.getElementById('calendar').src = loc;
}</code>
<code class="html"><iframe id="calendar" src="about:blank" width="1000" height="450" frameborder="0" scrolling="no"></iframe></code>
<code class="html"><input name="calendarSelection" type="radio" onselect="go('http://calendar.zoho.com/embed/9a6054c98fd2ad4047021cff76fee38773c34a35234fa42d426b9510864356a68cabcad57cbbb1a0?title=Kevin_Calendar&amp;type=1&amp;l=en&amp;tz=America/Los_Angeles&amp;sh=[0,0]&amp;v=1')" />Day</code>

However, this code fails to perform its intended action. The issue lies in a common programming error: improper use of brackets when referencing the 'calendar' iframe.

The correct syntax should be:

document.getElementById('calendar').src = loc;

Instead of the erroneous:

document.getElementById['calendar'].src = loc;

The single quotes surrounding 'calendar' in the latter example create a string, which results in a reference to a nonexistent element. By using square brackets, we are correctly referring to the iframe with the id 'calendar'.

Once this correction is made, the code should function as expected, smoothly updating the iframe's src attribute when a radio button is clicked.

The above is the detailed content of How to Correctly Modify iFrame Source Using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn