HTML + JS - 添加新文件按钮时文件名重置为文本

时间:2015-08-30 15:15:41

标签: javascript html file reset filechooser

我有一个添加按钮,就像这样,添加更多<input type="file">enter image description here

它确实有效,当我点击按钮时,它会调用一种方法来添加新的文件选择器。

HTML:

<div class="row" id="attachments_row">
          <div class="coffee-span-4">
            <label class="label label-1">Attachments</label>
          </div>
          <div class="coffee-span-6" id="attachments">
            <div id="attachment_inner">
                <input id="file_button" type="file" name="fileUpload0" size="50" /> 
                <sf:errors path="filepath" cssClass="rfqerror"></sf:errors>
            </div>
            <input type="button" value="+" style="float: left; margin-top: 10px; margin-bottom: 10px; padding: 5px;" onclick="makeNewAttachment();"/>
          </div>

          <div class="coffee-span-2" id="file-upload-button">
          </div>

          <br>
</div>

JS:

function makeNewAttachment() {
    var ai = document.getElementById("attachment_inner").innerHTML;
    var index = document.getElementById("attachment_inner").children.length;
    var ai_new = ai + "<input id='file_button' type='file' name='fileUpload" + index + "' size='50' />";
    document.getElementById("attachment_inner").innerHTML = ai_new;
}

但是当我选择文件时,文件名会重置为No file chosen

选择一个文件:

enter image description here

点击添加,重置?!?!?!?

enter image description here

有谁知道为什么?! 我让每个名字都不同,我认为就是这样,但是没有!

1 个答案:

答案 0 :(得分:1)

问题在于您复制了div #attachment_inner中的HTML文本,而不是div对象子项的文档对象。表示文件选择器input的文本没有表示最近选择的文件名的属性。该信息位于input对象中。虽然该对象是从HTML文本构建的,但该文本不会被重写以反映新信息,例如所选文件的名称。

解决方案是使用cloneNode()制作要复制的对象的深层副本。

在下面的代码段中,我正在克隆包含文件选择器的div,这样您还可以获得sf:errors标记的副本以及您可能希望与按钮一起使用的其他内容。此外,容器div使布局更容易。为避免多个div具有相同的id,我将id="attachment_inner"更改为class="attachment_inner"

function makeNewAttachment() {
    var attachments = document.getElementById('attachments'),
        choosers = attachments.getElementsByClassName('attachment_inner'),
        numChoosers = choosers.length,
        newChooser = choosers[numChoosers - 1].cloneNode(true),
        input = newChooser.getElementsByTagName('input')[0];
    attachments.insertBefore(newChooser, document.getElementById('plusButton'));
    input.name = input.name.replace(/\d+$/, '' + numChoosers);
}
<div class="row" id="attachments_row">
          <div class="coffee-span-4">
            <label class="label label-1">Attachments</label>
          </div>
          <div class="coffee-span-6" id="attachments">
            <div class="attachment_inner">
                <input type="file" name="fileUpload0" size="50" /> 
                <sf:errors path="filepath" cssClass="rfqerror"></sf:errors>
            </div>
            <input id="plusButton" type="button" value="+" style="float: left; margin-top: 10px; margin-bottom: 10px; padding: 5px;" onclick="makeNewAttachment();"/>
          </div>

          <div class="coffee-span-2" id="file-upload-button">
          </div>

          <br>
</div>