I have been working on previewing multiple images before they are uploaded and tried using @ratan-paul response to the "Preview an image before it is uploaded" quite useful. However when I tried to tweak the code a bit I got a rather unexpected result. What I did was to create a <span>
tag for each <image>
to add some styling options. Here's the jQuery code I ended up with:
$(function () {
var span_id = "";
function readURL(input) {
for(var i =0; i< input.files.length; i++){
var span = $('<span>');
span_id = "span"+i;
span.attr('id',span_id);
span.appendTo('#img-previews');
if (input.files[i]) {
var reader = new FileReader();
reader.onload = function (e) {
var img = $('<img id="dynamic">');
img.attr('src', e.target.result);
img.attr('height','150px');
img.attr('width','200px');
img.appendTo("#"+span_id);
};
reader.readAsDataURL(input.files[i]);
}
}
}
$("#imgUpload").change(function(){
readURL(this);
});
});
Now the strange thing is that when I run the code above I create a <span>
tag for each image but all the images get crammed into the last <span>
created. On the other hand if i debug the script I get the wanted result where each image is inserted into its own <span>
tag. I'm kinda baffled by this so if anyone has any ideas as to why this is happening or how to avoid it would appreciate the assistance.
Here is a screen grab of when I run the script without debugging:
And here is a screen grab of the result when stepped through with the js debugger