Junaid afzal
Junaid afzal

Reputation: 119

How To Remove selected file in Javascript/Jquery

I have a form that allows users to upload multiple images. Users has an option to remove Images one by one if they don't want to upload that particular image.

Now, How to remove the value from the file type of the one that they removed (e.g. didn't want to upload)?

I have tried using ($('input').val("")) but it works only for single image not for multiple images. If I used this for multiple image then all uploaded images value become empty instead of that particular image that user want to remove.. Below is my Code:-

HTML

<input type="file" id="files2" name="cert_img" multiple>
<output id="list2"></output>

Javascript

    var count2=0;
    function handleFileSelect2(evt) {
    var $fileUpload = $("input#files2[type='file']");
    count2=count2+parseInt($fileUpload.get(0).files.length);

    var files = evt.target.files;
    for (var i = 0, f; f = files[i]; i++) {
    if (!f.type.match('image.*')) {
    continue;
    }
    var reader = new FileReader();

    reader.onload = (function (theFile) {
    return function (e) {
    var span = document.createElement('span');
    span.innerHTML = ['<img class="thumb" id="image_X" src="', e.target.result, '" title="', escape(theFile.name), '"/><span class="remove_img_preview"></span>'].join('');
    document.getElementById('list2').insertBefore(span, null);
                };
            })(f);

    reader.readAsDataURL(f);
        }
    }

    $('#files2').change(function(evt){
    handleFileSelect2(evt);
    });  

    $('#list2').on('click', '.remove_img_preview',function () {
        $(this).parent('span').remove();

        //$('input').val("");



    });

Thanks in advance..

Upvotes: 1

Views: 4585

Answers (1)

Mohammad
Mohammad

Reputation: 21499

According to this question you can't change FileList content because it is readonly.

But if you want to remove a file of FileList, you can create a new object and set to it files that you want to upload. Then use created object to upload files. Run my example and select multiple files. Then click on any file that you want to delete. After delete files, see browser console.

var files;

$("#files").on("change", function(e){
   files = $("#files")[0].files;
   $.each(files, function(index, value){
       $("ol").append("<li data-index='"+index+"'>"+ value.name +"</li>");
   }); 
});

$(document).on("click", "li", function(){
   var newFiles = {};
   var index = $(this).index();
   
   $("li:nth-child(" + (index + 1) + ")").remove(); 
  
   $("li").each(function(index, element){    
       var dataIndex = $(element).attr("data-index");
       newFiles[index] = files[dataIndex];
   }); 
   console.log(newFiles);
});
li:hover {
    color: red;
    cursor: default;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" id="files" multiple>
<ol></ol>

Upvotes: 1

Related Questions