I’m using ASP.NET. Here in this razor page (cshtml) I’m trying to create a function where user can select multiple images, preview them, along with a remove button for each individual image. Just like how we can add photos and remove one by one on Facebook. Right now I have this html and a javascript code. The problem is, when I select 2 images A and B, I remove image A and then submit the form, image B is gone too. Which means the remove button resets the entire file input including the ones I didnt intend to remove. Why is that? I already have a for loop that iterates through each image, why is it clearing the entire input
<div class="form-group photos-group">
<label asp-for="MediaFiles" class="control-label"></label>
<input type="file" name="MediaFiles" multiple class="form-control" onchange="previewAdditionalPhotos(event)" />
<span asp-validation-for="MediaFiles" class="text-danger"></span>
<div class="additional-photos-preview"></div>
</div>
<div class="form-group">
<img src="#">
</div>
<script>
function previewAdditionalPhotos(event) {
var previewContainer = document.querySelector('.additional-photos-preview');
var files = event.target.files;
for (var i = 0; i < files.length; i++) {
var file = files[i];
if (file.type.match('image.*')) {
var reader = new FileReader();
reader.onload = function (e) {
var image = document.createElement('img');
image.className = 'preview-image';
image.src = e.target.result;
var removeButton = document.createElement('button');
removeButton.innerHTML = 'Remove';
removeButton.className = 'btn btn-danger remove-button';
removeButton.addEventListener('click', function () {
var previewDiv = this.parentNode;
var fileInput = document.querySelector('input[type="file"]');
fileInput.value = null;
previewContainer.removeChild(previewDiv);
});
var previewDiv = document.createElement('div');
previewDiv.appendChild(image);
previewDiv.appendChild(removeButton);
previewContainer.appendChild(previewDiv);
}
reader.readAsDataURL(file);
}
}