zaki dev-inbox
zaki dev-inbox

Reputation: 11

Show mulitple images after event change using jquery

I have a mulitple input file and I will want to display the selected images in a div. I tried with this code but it just shows me the first image

I try with this :

function readURL(input) {
  var reader = new FileReader();

  reader.onload = function(e) {
    for (var i = 0; i <= input.files.length; i++) {
      var imgId = $('<img />', {
        id: 'show_bultin_paie-' + input.files[i].lastModified,
        alt: 'MyAlt'
      });
      imgId.appendTo($('#imagediv'));
      $(imgId).attr('src', e.target.result);
    }

  }

  reader.readAsDataURL(input.files[0]);

}
}
$('#file_test').change(function(event) {
  readURL(this);
});

Upvotes: 0

Views: 38

Answers (1)

I wrestled a bear once.
I wrestled a bear once.

Reputation: 23379

You're not looping all the files, you're only reading the first one (reader.readAsDataURL(input.files[0]);). Use let instead of var since you're doing async stuff inside the loop.

function readURL(input) {
  for (let i = 0; i < input.files.length; i++) {
    var reader = new FileReader();
    reader.onload = function(e) {
      $('#imagediv').append("<img src='"+e.target.result+"'>");
    }
    reader.readAsDataURL(input.files[i]);
  }
}



$('#file_test').change(function(event) {
  readURL(this);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type=file id=file_test multiple accept='image/png, image/jpg, .png, .jpg'>
<div id=imagediv></div>

Upvotes: 1

Related Questions