I have a multiple image preview function. Image preview works on first time. But on second time, the image preview gets doubled using jquery append.
Here's my HTML code:
<div class="col-sm-6">
<div class="file-upload-container">
<div class="row">
</div>
<input type="file" multiple class="d-none" name="files">
<button type="button" class="upload-file btn btn-primary">Browse Files</button>
</div>
</div>
<div class="col-sm-6">
<div class="file-upload-container">
<div class="row">
</div>
<input type="file" multiple class="d-none" name="files">
<button type="button" class="upload-file btn btn-primary">Browse Files</button>
</div>
</div>
Here's my Script code:
$('.upload-file').on('click', function() {
$(this).parent().find('input[type="file"]').click();
$(this).parent().find('input[type="file"]').on('change', function(event) {
console.log("test");
var input = this;
var reader = new FileReader();
reader.onload = function (e) {
var imageTemplate = '<div class="col-xs-4">' +
'<div class="thumbnail">' +
'<img src="'+e.target.result+'">' +
'<input type="hidden" name="'+$(input).attr('name')+'[]" value="'+e.target.result+'">' +
'</div>' +
'</div>';
$(input).parent().find('.row').append(imageTemplate);
}
reader.readAsDataURL(this.files[0]);
})
})
Here's the fiddle: https://jsfiddle.net/2wpt74cx/1/
question from:
https://stackoverflow.com/questions/65948021/javascript-filereader-image-preview-gets-doubled-every-choose 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…