views:

210

answers:

1

I have a simple page with a single rendered iFrame. There's a link called "Add File" and unobtrusively I would like to attach an event to the "Add File" anchor so that when clicked, it inserts a new iFrame below the existing one with the ID of the iFrame incremented.

An example of the iFrame would be:

<iframe name="uploadForm1" id="uploadForm1" src="<%= upload_file_url %>" height="50" width="800" frameborder="0" scrolling="no"></iframe>

Then when clicking the "Add File" button I would end up with:

<iframe name="uploadForm1" id="uploadForm1" src="<%= upload_file_url %>" height="50" width="800" frameborder="0" scrolling="no"></iframe>
<iframe name="uploadForm2" id="uploadForm2" src="<%= upload_file_url %>" height="50" width="800" frameborder="0" scrolling="no"></iframe>

What would be the best approach (jQuery or Prototype) to accompish this?

It seems very trivial, however, because of the fact that I need to render the upload_file_url route, I'm not too sure how to approach it without wasting a whole lot of time!

Any assistance is appreciated!

+5  A: 

This should do it for you:

var g_maxNum = 1; // The latest iframe number

function copyIframe()
{
    // Get the latest iframe
    var iframe = document.getElementById('uploadForm' + g_maxNum);
    g_maxNum++

    // Create a new iframe by cloning the existing one
    var newIframe = iframe.cloneNode(true);
    // Update the properties
    newIframe.name = 'uploadForm' + g_maxNum;
    newIframe.id = newIframe.name

    // Insert it after the last iframe
    iframe.parentNode.insertBefore(newIframe, iframe.nextSibling);
}
Greg
Beautifully written, however, it's stuck on 'iframe.parentNode', which is returning null. Troubleshooting now.
mwilliams
Oops, I had an extra .cloneNode in there (the first line of the function) - fixed
Greg
Thank you very much. I have Yahuda's jQuery book, I really need to dig into it. I know I've seen the clone functions before but wasn't even close to that mindset; this was a very elegant solution. Thanks!
mwilliams