THE CASE
I am building an image upload with preview. On selecting multiple images, a preview is generated with a delete icon. This is working. The problem is the input file field is not counting correctly when deleting files from the image array.
THE CODE
The input HTML:
<input type="file" class="form-control" id="image" name="image[]" multiple>
Then, the code I got from (https://stackoverflow.com/a/68252788/910654). Here files are deleted when clicking 'onclick=deleteFile'.
--> Also working, however: the input field is not updating the count correctly when using more than three images. It gets stuck on 2 or 3 in the input field when deleting an item (given as: [i]).
function deleteFile(index) {
filelistall = $('#image').prop("files");
var fileBuffer=[];
Array.prototype.push.apply( fileBuffer, filelistall );
fileBuffer.splice(index, 1);
const dT = new ClipboardEvent('').clipboardData || new DataTransfer();
for (let file of fileBuffer) { dT.items.add(file); }
filelistall = $('#image').prop("files",dT.files);
$("#image-row-"+index).hide();
}
When selecting multiple images, this shows the previews correctly:
$('#image').change(function(){
$("#preview").html('');
for (var i = 0; i < $(this)[0].files.length; i++) {
var name = this.files[i].name;
$("#preview").append('<div class="row mt-2" id="image-row-'+[i]+'">
<div class="col-2"><img src="'+window.URL.createObjectURL(this.files[i])+'" class="img-fluid"/></div>
<div class="col-8"> '+ name+'</div>
<div onclick=deleteFile('+[i]+') class="col-2 deleteFile" data-name="'+[i]+'"><i class="mdi mdi-delete mdi-24px"></i></div>
</div>');
}
});
THE QUESTION
Does anyone know how to get the deleteFile() function to count correctly when deleting files?