2

Possible Duplicate:
In JavaScript can I make a “click” event fire programmatically for a file input element?

I wanted to make single click upload so I hide the <form> inside <iframe> like this (I just typed <iframe> tags around <form> to hide the form):

<iframe id="iframe" name="iframe" height="1" width="1" frameborder="0">
    <form id="form1" enctype="multipart/form-data" method="post" action="uploaded.php">
        <div class="row">
        <label for="file">Select a File to Upload (up to 20MB)</label><br />
        <input type="file" name="file" id="file" size="40" onchange="uploadFile()" />
        </div>
    </form>
</iframe>

Then outside the <iframe> I made a button:

<div align="center">
    <input type="button" value="Upload" align="center" onclick="browse();" />
</div>

the browse() javascript is this:

function browse()
{
    var iframe = document.getElementById.("iframe");
    var input = iframe.contentDocument || iframe.contentWindow.document;
    input.getElementById('file').click();
}

but it not working. The browse file dialog does not open. I'm using Firefox 17. Is there a way to click() on <input> inside <iframe> or any other one-click upload solution, but still using my uploadFile() AJAX function?

function uploadFile() {
        var fd = new FormData();
        fd.append("file", document.getElementById('file').files[0]);
        var xhr = new XMLHttpRequest();
        xhr.upload.addEventListener("progress", uploadProgress, false);
        xhr.addEventListener("load", uploadComplete, false);
        xhr.addEventListener("error", uploadFailed, false);
        xhr.addEventListener("abort", uploadCanceled, false);
        xhr.open("POST", "uploaded.php");
        xhr.send(fd);
      }

EDIT: this is working when the form is not in iframe, so my question is not wheter or not can I use click() on <input type="file">. I can and it is working in Firefox 17. My question is how to use click() on <input type="file"> inside <iframe>.

Community
  • 1
  • 1
cikatomo
  • 1,620
  • 2
  • 23
  • 32

2 Answers2

-1

The JavaScript should be throwing an error since you have a type with an extra .

var iframe = document.getElementById.("iframe");  
                                    ^-- typo
epascarello
  • 204,599
  • 20
  • 195
  • 236
-1

The child elements of an <iframe> are alternative content to use if the browser doesn't support iframes. They do not form part of the document loaded into the frame (which is what contentDocument would access).

Your problem (or at least your first problem) is that you are trying to use that as a hack to hide content. Don't do that.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335