I'm trying to build a image preview for uploaded files but i want the images to update their previews when user re-uploades on the same input. The code that i wrote for multiple images works but the one with primary image doesn't.
$(function() {
// Multiple images preview in browser
var imagesPreview = function(input, placeToInsertImagePreview, type) {
if (type === 'multiple') {
if ($('#gallery').children().length > 1) {
$('#gallery').children().slice(1).remove();
}
} else if (type === 'primary') {
$('#primary').empty();
}
if (input.files) {
var filesAmount = input.files.length;
for (i = 0; i < filesAmount; i++) {
var reader = new FileReader();
reader.onload = function(event) {
$($.parseHTML('<img>')).attr('src', event.target.result).appendTo(placeToInsertImagePreview).addClass('col rounded upload-img shadow-sm');
}
reader.readAsDataURL(input.files[i]);
}
}
var $fileUpload = $("input[type='file']");
if (parseInt($fileUpload.get(0).files.length) > 2) {
alert("You can only upload a maximum of 2 files");
}
};
$('#gallery-photo-add').on('change', function() {
imagesPreview(this, 'div.gallery', 'multiple');
});
$('#primary').on('change', function() {
imagesPreview(this, 'div.primary', 'primary');
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="file" name="image[]" multiple id="gallery-photo-add">
<div class="card primary" id="primary"></div>
<div class="gallery row" id="gallery"></div>
I tried to console log inside
}else if (type === 'primary') {
$('#primary').empty();
console.log('deleted');
}
It displays deleted but does nothing. Also i've tried something like this too
}else if (type === 'primary') {
$('#primary').children().remove();
}
Still no luck. What am i missing?
Here's the full inputs
<div class="form-group">
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text" id="inputGroupFileAddon01">@lang('product.upload')</span>
</div>
<div class="custom-file">
<input type="file" class="custom-file-input" id="primary" name="primaryimg" aria-describedby="primary">
<label class="custom-file-label" for="primaryimg">Choose file</label>
</div>
</div>
<input type="file" name="image[]" multiple id="gallery-photo-add">
<div class="card primary" id="primary"></div>
<div class="gallery row" id="gallery"></div>
</div>
<button type="submit" class="btn btn-primary">Submit</button>