how do you remove a file from the upload control before uploading it using jquery?

From your code, I can see that you forget to remove the dom that why the file still exists.

Another, to make the code simple we can attach data-index inside the delete button to remember the file index when we’re deleting it will be easy than compare the string of filename.

Here is the modified code.

var fileInput = document.getElementById('inputfile');
var fileListDisplay = document.getElementById('allfiles');

var fileList = [];
var renderFileList, sendFile;

fileInput.addEventListener('change', function (evnt) {
  fileList = [];
  for (var i = 0; i < fileInput.files.length; i++) {
    fileList.push(fileInput.files[i]);
  }
  renderFileList();
});

renderFileList = function () {
  fileListDisplay.innerHTML = '';
  fileList.forEach(function (file, index) {
    var fileDisplayEl = document.createElement('p');
    fileDisplayEl.innerHTML = `${file.name} <button data-index="${index}" class='deletfile'>X</button>`;
    fileListDisplay.appendChild(fileDisplayEl);
  });
};


$(document).on('click','.deletfile', function()
{
  const index= $(this).attr('data-index');
  fileList.splice(parseInt(index, 10), 1);
  $(this).parent().remove();
});

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top