I have the following code to view the images uploaded under <input type="file"
$(document).on("change", ".files", function(e) {
var files = e.target.files,
filesLength = files.length;
$(this).find('.pip').remove();
for (var i = 0; i < filesLength; i++) {
var f = files[i]
var fileReader = new FileReader();
fileReader.onload = (function(e) {
var file = e.target;
$("<span class=\"pip\">" +
"<img class=\"imageThumb\" src=\"" + e.target.result + "\">" +
"<br/><span class=\"remove\"><i class='fa fa-times-circle'></i></span>" +
"</span>").insertAfter(".file-upload");
$(".remove").click(function(){
$(this).parent(".pip").remove();
});
});
fileReader.readAsDataURL(f);
}
});
The class file-upload get duplicated on a click of a button. So i want to target the current div like this insertAfter($(this).find(".file-upload"))? Does that even work? I tried to do but it didn't work. How can I achieve that?
I tried to use append but that did not help either.
Edit My HTML
<div class="medi">
<div class="file-upload">
<input type="file" class="files" name="images[]" multiple="">
<img src="/upload.png" style="position: relative;top: 11px;height: 16px;width: 16px;margin-left: 8px;">
<span class="upload-text">Upload</span>
</div>
</div>
This section gets duplicated.
In you code this refers to input, so you need to find closest .file-upload parent, you can use parent but you need to keep that structure (I prefer closest)
Don't add events in for-loop becouse if you select 3 files your first remove element will have 3 click events, 2 on the second and one on the last one
$(document).on("change", ".files", function (e) {
var files = e.target.files,
filesLength = files.length;
//this reffer's to <input type="file" class="files" .. so you need to get closest parent .file-upload
let div = $(this).closest(".file-upload");
$(div).find('.pip').remove();
for (var i = 0; i < filesLength; i++) {
var f = files[i]
var fileReader = new FileReader();
fileReader.onload = (function (e) {
var file = e.target;
$("<span class=\"pip\">" +
"<img class=\"imageThumb\" src=\"" + e.target.result + "\">" +
"<br/><span class=\"remove\"><i class='fa fa-times-circle'></i></span>" +
"</span>").insertAfter($(div));
});
fileReader.readAsDataURL(f);
}
$(div).find(".remove").click(function () {
$(this).parent(".pip").remove();
});
});
img {
max-width: 80px;
max-height: 80px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="medi">
<div class="file-upload">
<input type="file" class="files" name="images[]" multiple="">
<img src="/upload.png" style="position: relative;top: 11px;height: 16px;width: 16px;margin-left: 8px;">
<span class="upload-text">Upload</span>
</div>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With