0

I'm creating file preview and delete functions in jQuery but when i delete preview element its should also delete array.

Html

 <div class="col-xs-6">
    <div class="btn btn-primary">
        <input multiple type="file" id="ImageBrowsers" />
    </div>
    <hr />
    <div id="Gallary">

    </div>
</div>

jQuery

$(document).ready(function () {
        $("#ImageBrowsers").change(function () {
            var File = this.files;
            for (var i in File) {
                if (typeof File[i] == 'object') {
                    ImageReader(File[i]);
                }                
            }
        });
    });
    // Image Preview Function 
    function ImageReader(File) {        
        var Reader = new FileReader;
        var Img = new Image;        
        Reader.readAsDataURL(File);
        Reader.onload = function (_File) {
            Img.src = _File.target.result;
            Img.onload = function () {
                var Height = this.height;
                var Width = this.width;
                var Type = File.type;
                var Size = File.size;
                console.log(File.name);
                $("#Gallary").append('<div class="thumbnail"><img class="img-responsive" src="' + (_File.target.result) + '"/><div class="caption"><a href="#" onclick="ClearPreview(this,\'' +  File.name + '\')"><i class="glyphicon glyphicon-trash"></i></a><p> Size: ' + (Size) + ',' + (Height) + 'x' + (Width) + ', Type: ' + (Type) +'</p></div></div>')                
                $("#Description").text();
            }
        }
    }

    function ClearPreview(Element, FileName) {
        var Name = FileName;
        $(Element).parents('div.thumbnail').remove();
        var Images = $("#ImageBrowsers")[0].files;

        for (var x in Images) {
            if (FileName == Images[x].name) {
                Images[x].remove();
            }
        }

i know remove function will not remove array but i have tried splice maybe i'm doing something wrong please help me to update file array as well.

Ray
  • 3,864
  • 7
  • 24
  • 36
  • 1
    Possible duplicate of [How do I remove a particular element from an array in JavaScript?](https://stackoverflow.com/questions/5767325/how-do-i-remove-a-particular-element-from-an-array-in-javascript) – Rudresha Parameshappa Aug 15 '18 at 16:00

1 Answers1

0

This would be the correct way to remove an element from an array:

Images.slice(x, 1);

But this would mess up the indexes in the array while the for loop is still running, so you could do something like this:

var indexesForDeletion = [];
for (var x in Images) {
    if (FileName == Images[x].name) {
        Images[x].remove();
        indexesForDeletion.push(x);
    }
}

indexesForDeletion.forEach(function(index){
    Images.slice(index, 1);
});
indexesForDeletion = [];
Ray
  • 3,864
  • 7
  • 24
  • 36