The issue is that when a file is removed, the entire input field is being cleared. To remove only the selected file, the following changes can be made to the ksHandleRemoveFile function:
- Instead of setting
fileInput.value = '', remove the selected file from thefilesarray usingsplice()method. - After removing the file from the
filesarray, update thefileIndexof the remaining files' remove buttons.
Here's the updated ksHandleRemoveFile function:
function ksHandleRemoveFile(evt) {
evt.preventDefault();
evt.stopPropagation();
let fileIndex = evt.target.dataset.fileIndex;
let fileInputId = evt.target.dataset.fileInputId;
let fileInput = document.getElementById(fileInputId);
let parentNode = evt.target.parentNode.parentNode;
if (parentNode) {
let files = evt.target.parentNode.parentNode.querySelectorAll('.file');
for (let i = 0; i < files.length; i++) {
if (i == fileIndex) {
files[i].parentNode.removeChild(files[i]);
// Remove the selected file from the files array
let newFiles = Array.from(fileInput.files);
newFiles.splice(i, 1);
fileInput.files = newFiles;
} else {
let removeButton = files[i].querySelector('button');
removeButton.dataset.fileIndex = i - (i > fileIndex ? 1 : 0);
}
}
}
}
Here's the updated JSFiddle: https://jsfiddle.net/7z5L8q1h/