4

I got the job to add a delete function to a html input with type "file", which can delete a single file from a list of multiple files. As you can see in the snippet below, deleting all files at once is easily done, but my function to delete one file at a certain index is not working.

function remove(i){ document.getElementById('files').files.splice(i, 1); } function removeAll(){ document.getElementById("files").value=null; }
<input id="files" type="file" multiple="multiple"> <button onclick="remove(1)">delete 1st</button> <button onclick="remove(2)">delete 2nd</button> <button onclick="remove(3)">delete 3rd</button> <button onclick="removeAll()">delete all</button>

Is there any way to make this remove()-function work?

1

2 Answers 2

1

You need to convert the object from document.getElementById('files') to an array first. Also .splice() returns the removed elements. So you need to store the array in a variable. After using .splice() on this array the array will contain the remaining elements:

function remove(i){ var myFiles = Object.entries(document.getElementById('files').files) Object.entries(myFiles.splice(i-1, 1)); // make sure to use i-1, not i console.log(myFiles); // const obj = Object.assign({}, myFiles ); use this to return it back to an obj } function removeAll(){ document.getElementById("files").value=null; }
<input id="files" type="file" multiple="multiple"> <button onclick="remove(1)">delete 1st</button> <button onclick="remove(2)">delete 2nd</button> <button onclick="remove(3)">delete 3rd</button> <button onclick="removeAll()">delete all</button>

Sign up to request clarification or add additional context in comments.

Comments

0

First, you need to spread input.files into an array.

Second, you need to call splice() on the array with index "i" ( remove(i) ) as the first argument and at the end - you specify that you want to remove only 1 item with the 2nd arguemnt - arr.splice(i, 1).

Finally, arr has deleted item according to your button click.

Also, you need to start your buttons from `remove(0)' because arrays start at 0.

function remove(i){ //document.getElementById('files').files.splice(i, 1); const input = document.getElementById('files') const arr = [...input.files]; arr.splice(i, 1); console.log(arr); } function removeAll(){ document.getElementById("files").value=null; }
<input id="files" type="file" multiple="multiple"> <button onclick="remove(0)">delete 1st</button> <button onclick="remove(1)">delete 2nd</button> <button onclick="remove(2)">delete 3rd</button> <button onclick="removeAll()">delete all</button>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.