Empty file input from .clone()

不想你离开。 提交于 2020-01-04 04:12:07

问题


I'm trying to clone a file input form, which every time I select a file then click "add more" to clone the file input, but it has copied the selected file in the input.

<input type="file" />
<span id="add-more-files">Add more</span>

jQuery:

$('#add-more-files').click(function()
{
   var cloned = $(this).prev().clone();
   $(cloned).insertBefore($(this));
});

Demo: jsFiddle.

Now whenever you select a file before cloning the previous, you can see it has the same file selected, I need it to be empty when cloned.

EDIT:

How would I be able to clone this, referring to Neal's answer?

<div class="wrap"><input type="file /></div>
<span id="add-more-files">Add more</span>

回答1:


what you can try is:

$('#add-more-files').click(function()
{
   var cloned = $(this).prev().clone();
   cloned.val(null);
   $(cloned).insertBefore($(this));
});

UPDATE
or if all the inputs will be copies from the previous just create a new one instead of cloning:

$('#add-more-files').click(function()
{
   var cloned = $(this).prev();
   $('<input>',{type:cloned.attr('type')}).insertBefore($(this));
});



回答2:


The only workable solution I found is to provide the file input field as a template that is hidden. Then a clone is created after the page is loaded to provide the first field.

It also works without an "add more" button, instead it adds a new file input field when the last one is filled in.

<div id="files">
    <input type="file" name="files" style="display: none;">
</div>
function AddUploadElement()
{
    var newUploadElement = $("#files").children(":first-child").clone();
    newUploadElement.css("display", "");

    $("#files").append(newUploadElement);
}

$(document).ready(function ()
{
    AddUploadElement();

    $("#files").on("change", "input", function ()
    {
        if ($(this).is(":last-child") == true)
        {
            AddUploadElement();
        }
    });
});

The cloning part is important because the template input field might have additional attributes.




回答3:


The jquery.fileupload plugin circumvents the issue of clearing file inputs like this:

var inputClone = input.clone(true);
$('<form></form>').append(inputClone)[0].reset();
input.after(inputClone).detach();

i.e. clone the input, append to a temporary form to reset it, and detach the input so that it can be appended to forms consecutively.

then you can input.replaceWith(inputClone);



来源:https://stackoverflow.com/questions/5598613/empty-file-input-from-clone

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!