Context
- In the simple form shown a
file
input element allows for multiple file uploads. - An image preview is generated for each file.
- When an image is clicked on, this preview image is deleted (for simplicity I haven't included a delete button, it is deleted when you click the image).
On a side note the image files are submitted via PHP in the backend and the backend code all works as expected.
When a number of files are attached via the files input element it creates an array which you can see via the console.log([...chooseFiles.files]);
line of code, which shows details of the files attached.
Problem
Can someone explain how when an image is clicked (and thus removed/ deleted visually) how you also remove that specific image from the chooseFiles.files array?
At the moment, because the image is only visually removed, the related image file is still submitted with the form.
Codepen: https://codepen.io/thechewy/pen/xxjQwLY
let chooseFiles = document.getElementById("choose-files");
let previewWrapper = document.getElementById("preview-wrapper");
chooseFiles.addEventListener("change", (e) => {
[...chooseFiles.files].forEach(showFiles);
console.log([...chooseFiles.files]);
});
function showFiles(file) {
let previewImage = new Image();
previewImage.classList.add("img");
previewImage.src = URL.createObjectURL(file);
previewWrapper.append(previewImage); // append preview image
// -- remove the image preview visually
document.querySelectorAll(".img").forEach((i) => {
i.addEventListener("click", (e) => {
e.target.remove();
});
});
}
form {
padding: 2rem;
background: red;
width: 50%;
}
input,
button {
display: block;
margin: 1rem 0;
}
.img {
width: 200px;
height: 200px;
object-fit: cover;
margin: 0 1rem;
}
img:hover {
cursor: pointer;
}
<form enctype="multipart/form-data" method="post">
<input id="choose-files" type="file" name="choose-files[]" multiple>
<button name="submit" id="submit">SUBMIT</button>
<div id="preview-wrapper"></div>
</form>