Will
Will

Reputation: 681

How does FileReader.onload work?

I am trying to preview the uploaded images, below is the code

$('#upload-photo').on('change', '.inventory-photo', function() {       
    if (this.files.length >= 1) {

        for (var i =0; i < this.files.length; i++) {
            $('#photo-preview').append('<img id="a'+ i + '"' + 'src="" />');
            var reader = new FileReader();

            reader.onload = function(e) {
                $('#a'+0).attr("src", e.target.result);
                console.log($('#a' + i));
            }

            reader.readAsDataURL(this.files[i]);
        }
    }
})

If i upload multiple images, it does not work correctly, and it only shows the last image. I find in the reader.onload, $('#a' + i) always is the index of last image. If i upload 2 images, it shows two #a1 in console; if i upload 3 images, it shows three #a2. why does this happen?

Upvotes: 0

Views: 586

Answers (1)

adeneo
adeneo

Reputation: 318212

You need a closure to keep the value of i, but jQuery has $.each, and it creates it's own closure

$('#upload-photo').on('change', '.inventory-photo', function() {       
    $.each(this.files, function(index, file) {
        var reader = new FileReader();
        reader.onload = function(e) {
            $('<img />', {
                id : 'a' + index,
                src: e.target.result
            }).appendTo('#photo-preview')
         }
         reader.readAsDataURL(file);
    });
});

FIDDLE

Upvotes: 2

Related Questions