【问题标题】:How to Remove one file of selected files from dynamic generated input file control in a html table如何从 html 表中的动态生成的输入文件控件中删除一个选定文件的文件
【发布时间】:2020-02-11 07:53:20
【问题描述】:
enter image description here我有一个动态添加行的html表,我在这个表中有3列第一列是下拉列表,第二列是动态生成的输入文件按钮,第三列是删除行.我为输入文件控件设置了“多个”类型以选择多个文件以及“删除”超链接以删除最终用户想要的特定文件,我可以从列表中删除文件,但实际上文件并未从输入文件控件中删除,即使从列表中删除特定文件,我也可以看到文件数没有减少。我还附上了屏幕截图,
我能够删除文件列表,但文件没有从输入文件控制中删除
但文件并未从输入文件控件中删除
【问题讨论】:
标签:
javascript
jquery
html
file
input
【解决方案1】:
您是否在单击删除时尝试过类似document.querySelector('input[type="file"]').value = null 的操作?
【解决方案2】:
除了使用内置输入,使用带有隐藏输入的标签,您还需要手动处理来自更改事件的文件,而不是在表单上使用序列化,您将创建一个 new FormData() 并将文件附加到它以及任何其他数据。
var Files = [];
$(document).ready(()=>{
$('input#files').on('change', (e)=>{
let files = e.target.files;
for(let i = 0; i < files.length; i++){
let file = files[i];
let div = document.createElement('div');
div.id = Files.length;
$(div).append(`${file.name} <span class="delete-file" data-id="${Files.length}">X</span>`);
$('div.files-container').append(div);
Files.push(file);
updateLabel();
}
});
$(document).on('click', 'span.delete-file', function(e){
let id = $(this).data('id');
$(this).parent().remove();
Files.splice(id, 1);
updateLabel();
});
});
function updateLabel() {
let text = 'Select Files';
if(Files.length > 1) text = `${Files.length} Files`;
else if(Files.length > 0) text = `${Files.length} File`;
$('#files-count').html(text);
}
label.custom-input{
display: inline-block;
border: 1px solid black;
padding: 5px;
border-radius: 5px;
cursor: pointer;
min-width: 150px;
}
label.custom-input input{
display: none;
}
.files-container{
display: flex;
flex-direction: column;
padding: 5px;
}
.files-container div{
padding: 5px;
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 2px;
border-bottom: 1px solid;
}
span.delete-file{
padding: 5px;
color: white;
background-color: red;
cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label for="files" class="custom-input">
<input id="files" type="file" multiple>
<span id="files-count">Select Files</span>
</label>
<div class="files-container">
</div>