• Home
  • How to delete a selected file from multiple input file from a button click – JavaScript

How to delete a selected file from multiple input file from a button click – JavaScript

Deleting a selected file from multiple input file using a button click can be done through a combination of HTML, CSS, and JavaScript.

In HTML, you would create a form element to allow the user to select multiple files. Within the form, you would also include a button element which would be used to delete the selected files.

<form>
<input type="file" multiple>
<button id="deleteButton">Delete</button>
</form>

In JavaScript, you would use the DOM API to access the file input and button elements, and attach an event listener to the button element that would listen for a click event. When the button is clicked, you would use the files property of the file input element to access the selected files, then use a loop to iterate over the files and remove them one by one.

const input = document.querySelector("input[type='file']");
const deleteButton = document.querySelector("#deleteButton");

deleteButton.addEventListener("click", function() {
for (let i = 0; i < input.files.length; i++) {
input.files[i] = null;
}
});

You might also want to clear the file input after the files are deleted, you can use the value property of the input element

input.value = "";

Alternatively, you can also implement this functionality with CSS, by adding and removing a class to change the visibility of the selected files.

Please note that this solution only removes the files selected in the file input element, not physically from the device. If you want to remove the files from your server, you will need to do this using the appropriate server-side technology.