I want to select multiple images and give those images a button so that user can delete the image as well. I'm able to do the preview of the image but I'm not able to delete the image after preview.
This is my javascript code
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
// Loop through the FileList and render image files as thumbnails.
for (var i = 0, f; f = files[i]; i++) {
// Only process image files.
if (!f.type.match('image.*')) {
continue;
}
var reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function(theFile) {
return function(e) {
// Render thumbnail.
var span = document.createElement('span');
span.innerHTML = ['<img class="thumb" src="', e.target.result,
'" title="', escape(theFile.name), '"/>'].join('');
document.getElementById('list').insertBefore(span, null);
};
})(f);
// Read in the image file as a data URL.
reader.readAsDataURL(f);
}
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
And this is my HTML code where id=list is the area where images are shown as thumbnails:
<div class="file-upload">
<div class="file-select">
<div class="file-select-button" id="fileName">Choose Image</div>
<div class="file-select-name" id="noFile"></div>
<input type="file" id="files" name="files[]" multiple />
</div>
</div>
</div>
<div class="col-lg-12 col-md-12 col-xs-12 xol-sm-12">
<output id="list"></output>
</div>
How to insert delete option with every image?
check this https://jsfiddle.net/dp722j27/10/
you can have a delete method like this
function deleteImage() {
var index = Array.from(document.getElementById('list').children).indexOf(event.target.parentNode)
document.querySelector("#list").removeChild( document.querySelectorAll('#list span')[index]);
totalFiles.splice(index, 1);
console.log(totalFiles)
}
and your render method like
var span = document.createElement('span');
span.innerHTML = ['<img width=100 class="thumb" src="', e.target.result,
'" title="', escape(theFile.name), '"/>', "<button onclick='deleteImage()'>delete</button>"].join('');
document.getElementById('list').insertBefore(span, null);
you can store the values in an array and handle it like
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