1

I have a file input field where I can select multiple files at once, and show all the selected files in a list with specific file removal functionality. Now I can remove the file from the list, but I couldn't find a way to remove the file also from the input field array. How can I remove the specific file from input field array too using jQuery. I don't want to use any plugin for this.

$('#uploadBtn').change(function(){
  $('#attachments').html('');
  var attachments = document.getElementById('uploadBtn');
  var item = '';
  for(var i=0; i<attachments.files.length; i++) {
    item += '<li>' + attachments.files.item(i).name +
      '&nbsp;&nbsp;<a href="#" id="'+ i +'" class="dlt-attch">Remove</a>' +
      '</li>';
    console.log(attachments.files.item(i).name);
  }
  $('#attachments').append(item);
  $('.dlt-attch').click(function(e){
    e.preventDefault();
    var id = $(this).attr('id');
    console.log(attachments.files);
    $(this).parent().remove();
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="uploadBtn" multiple="multiple" type="file" name="attachments[]" class="upload" />
<ul id="attachments" style="margin-top: 10px; list-style-type: decimal;"></ul>

1

1 Answer 1

1

Unfortunately you can't remove a file from that list because they are stored in a read-only FileList object: https://developer.mozilla.org/en-US/docs/Web/API/FileList

As an alternative you can keep your own array of files, but then you will need to use your own implementation to upload the files.

There is a similar question that was asked a few years ago but it is still valid: How do I remove a file from the FileList - There is an answer that uses XMLHttpRequest to manually upload the files.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.