Clone a file input element in Javascript

后端 未结 4 1539
囚心锁ツ
囚心锁ツ 2020-11-28 11:55

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,

4条回答
  •  半阙折子戏
    2020-11-28 12:43

    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");
    

提交回复
热议问题