Changing An IFrame Source From A Drop-Down List Via JavaScript / DOM

Recently asked on Yahoo! Answers:

I am looking for a drop down box that links to a iframe. . .?

the same drop down box that goes with a form that changes based on what is in the drop down box. HELP Please!!!

This is a very easy task to accomplish, provided you know the basics of Document Object Model (DOM) manipulation and JavaScript. As always, I’ll have a link to a working demo and downloadable code at the end of this entry.

Step 1: Create The XHTML Form

To begin, we need some simple HTML elements:

  • A basic form;
  • A drop-down (select) list that will contain the URLs we want to use;
  • An iFrame that will display the page we select from the drop-down list.

Note that we add the name of our JavaScript function, setIframeSource(), to the onchange event for the select (drop-down) list.

<form id="form1" method="post">
	<label>
		Select A Location:
		<select id="location" onchange="setIframeSource()">
			<option value="dummy.html">Select a location ...</option>
			<option value="http://www.yahoo.com">Yahoo!</option>
			<option value="http://answers.yahoo.com">Yahoo! Answers</option>
			<option value="http://www.mozilla.org">Mozilla.org</option>
			<option value="http://www.dunkindonuts.com">Dunkin Donuts</option>
		</select>
	</label>
</form>
<p>&nbsp;</p>
<iframe id="myIframe" src="dummy.html" width="800" height="400" frameborder="0" marginheight="0" marginwidth="0"></iframe>

Step 2: The JavaScript Function

The JavaScript function that powers our IFrame is simple as pie:

  • We set variables to represent the select list and the IFrame in our document.
  • We set the value of a variable we called theUrl to be the value of the currently selected option from the drop-down list.
  • We set the source of the IFrame to be theUrl.
function setIframeSource() {
	var theSelect = document.getElementById('location');
	var theIframe = document.getElementById('myIframe');
	var theUrl;

	theUrl = theSelect.options[theSelect.selectedIndex].value;
	theIframe.src = theUrl;
}

Every time we change the value in the drop-down list, the IFrame’s source will also be changed. It’s that simple.

You can see a working demo of this script here:

http://www.dougv.com/demo/js_ddl_iframe/

Just save the page to your computer and tinker with it to suit your needs. As always, I distribute code under the latest version of the Creative Commons Attribution / Share-Alike License.


Leave a Reply