Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

delete button on image upload with preview

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?

like image 948
juhi Avatar asked Dec 20 '25 04:12

juhi


1 Answers

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

like image 130
Aswin Ramesh Avatar answered Dec 21 '25 16:12

Aswin Ramesh