Clone a file input element in Javascript

44,586

Solution 1

Guessing that you need this functionality so you can clone the input element and put it into a hidden form which then gets POSTed to a hidden iframe...

IE's element.clone() implementation doesn't carry over the value for input type="file", so you have to go the other way around:

// Clone the "real" input element
var real = $("#categoryImageFileInput_" + id);
var cloned = real.clone(true);

// Put the cloned element directly after the real element
// (the cloned element will take the real input element's place in your UI
// after you move the real element in the next step)
real.hide();
cloned.insertAfter(real);   

// Move the real element to the hidden form - you can then submit it
real.appendTo("#some-hidden-form");

Solution 2

In jQuery fileupload widget there is a file input replace method to get around the change event listener only firing once.

https://github.com/blueimp/jQuery-File-Upload/blob/master/js/jquery.fileupload.js#L769

(_replaceFileInput method in jquery.fileupload.js)

Share:
44,586
Anti-Dentite
Author by

Anti-Dentite

Updated on July 09, 2022

Comments

  • Anti-Dentite
    Anti-Dentite almost 2 years

    I have a file input element that needs to be cloned after the user has browsed and selected a file to upload. I started by using obj.cloneNode() and everything worked fine, that is until I tried using it in IE.

    I've since tried using jQuery's clone method as follows:

    var tmp = jQuery('#categoryImageFileInput_'+id).clone();
    var clone = tmp[0];
    

    Works as expected in FireFox, but again not in IE.

    I'm stuck. Anyone have some suggestions?

  • sjbwylbs
    sjbwylbs over 11 years
    Current in Chrome version 23.0.1271.101 is still fail now.
  • Sanjeev
    Sanjeev almost 10 years
    Thanks Mark, this is an good solution . I was facing same problem with IE8.
  • Tom
    Tom about 8 years
    This is a good approach - simply move the input to the desired place and then recreate it
  • Muhammad Omer Aslam
    Muhammad Omer Aslam about 5 years
    in chrome it does not work, the file browse button is never displayed, although the element is cloned and can be seen in the source code