Ask a Jedi: Working with IFrames, JavaScript, and how ColdFusion 8 makes life easier

Jay asks:

I have a select box and an iframe and I would like to change the content of the iframe based on what is selected in the select box. Is that possible?

So this one threw me for a bit because I couldn't honestly remember the last time I worked with an iframe. But I worked out a solution, and when I realized what a great opportunity this would be to showcase ColdFusion 8, I thought I'd share what I found. First though let's answer the original question. How do you change the contents of an iframe? You can set the src property of an iframe via JavaScript. Here is a super simple example:

<script> function updateContent() { var foodd = document.getElementById("foo"); var foovalue = foodd.options[foodd.selectedIndex].value; if(!foovalue) return; var myframe = document.getElementById("myiframe"); myframe.src = "ilayer.cfm?id="+foovalue; } </script> <select id="foo" onChange="updateContent()"> <option></option> <option value="1">One</option> <option value="2">Two</option> <option value="3">Three</option> </select>

<iframe id="myiframe" src="ilayer.cfm" />

What I've done is add a onChange event handler to my drop down box. This calls JavaScript code that then changes the src (location) of the iframe. The code for ilayer.cfm is:

<cfparam name="" default="">

<cfif len(> <cfoutput> is</cfoutput> </cfif>

All I'm doing is echoing back the value of URL.ID. So... pretty simple. But what is cool is how much easier this gets in ColdFusion 8. Let's look at a sample:

<select id="foo"> <option></option> <option value="1">One</option> <option value="2">Two</option> <option value="3">Three</option> </select>

<cfdiv bind="url:ilayer.cfm?id={foo}" width="200" height="200" />

So first off - no more JavaScript. At all. Me likely. I changed the iframe to a cfdiv, and to be honest, this looks a bit different from the iframe, but I'm sure you could CSS it up a bit. Lastly, I added a bind to the cfdiv. When I change my drop down (foo), the div generated by ColdFusion will notice the change and pass the value along.

Raymond Camden's Picture

About Raymond Camden

Raymond is a developer advocate. He focuses on JavaScript, serverless and enterprise cat demos. If you like this article, please consider visiting my Amazon Wishlist or donating via PayPal to show your support. You can even buy me a coffee!

Lafayette, LA