7

I'm using a input type file multiple to update some pictures. Before upload, the page shows a miniature of each picture. I would like to do a remove link to each picture, and when the user clicks, the picture disapear and the file is removed from input.

I try to use this code below:

HTML:

<input id="midiasUpload" multiple="multiple" type="file" name="midias" accept="image/x-png,image/gif,image/jpeg" /> 
<div id="midiaDigital"></div>

Javascript:

$(document).ready(function() {

$("#midiasUpload").on('change', function() {
    //Get count of selected files
    var countFiles = $(this)[0].files.length;
    var imgPath = $(this)[0].value;
    var extn = imgPath.substring(imgPath.lastIndexOf('.') + 1).toLowerCase();
    var image_holder = $("#midiaDigital");
    image_holder.empty();
    if (extn == "gif" || extn == "png" || extn == "jpg" || extn == "jpeg") {
      if (typeof(FileReader) != "undefined") {
        //loop for each file selected for uploaded.
        for (var i = 0; i < countFiles; i++) 
        {
          var reader = new FileReader();
          reader.onload = function(e) {
              $(image_holder).append('<div class="form-group row">' +
                                      '<div>' +
                                      '<div class="col-md-6">' +                              
                                      '<img src="' + e.target.result + '" class="thumb-image img-responsive">' +
                                      '<input type="text" class="form-control input-sm" name="midiaDigitals[' + i + '].legenda" placeholder="Digite a descrição da mídia digital"/>' + 
                                      '<a href="#" class="remove_field1">Remover</a>' + //add input box
                                      '</div>' +
                                      '</div>' +
                                      '</div>'); 


          }
          image_holder.show();
          reader.readAsDataURL($(this)[0].files[i]);
        }
      } else {
        alert("O browser não suporta upload de arquivos.");
      }
    } else {
      alert("Formato de arquivo inválido");
    }
  });

$(midiaDigital).on("click",".remove_field1", function(e){ //user click on remove text
    e.preventDefault(); $(this).parent('div').remove(); 
})

}); 

Using this code, the "preview" pictures appear with the "remove" link. When I click in the "remove", the preview picture are deleted, but the file continues selected. What should I do?

2 Answers 2

2

You can do it simply via jQuery in one line: $('#midiasUpload').val('');. It resets input value. Here is the snippet:

function select(el) {
  img = el;
}
var img;
var input;
$(document).ready(function() {
  $("#midiasUpload").on('change', function() {
    var countFiles = $(this)[0].files.length;
    input = $(this)[0];
    console.log('Input value after upload: ', input.value)
    var imgPath = input.value;
    img = imgPath;
    var extn = imgPath.substring(imgPath.lastIndexOf('.') + 1).toLowerCase();
    var image_holder = $("#midiaDigital");
    image_holder.empty();
    if (extn == "gif" || extn == "png" || extn == "jpg" || extn == "jpeg") {
      if (typeof(FileReader) != "undefined") {
        for (var i = 0; i < countFiles; i++) {
          var reader = new FileReader();
          reader.onload = function(e) {
            $(image_holder).append('<div class="form-group row">' +
                                   '<div>' +
                                   '<div class="col-md-6">' +                             
                                   '<img src="' + e.target.result + '" class="thumb-image img-responsive" onclick="select($(this))">' +
                                   '<input type="text" class="form-control input-sm" name="midiaDigitals[' + i + '].legenda" placeholder="Digite a descrição da mídia digital"/>' + 
                                   '<a href="#" class="remove_field1">Remover</a>' + //add input box
                                   '</div>' +
                                   '</div>' +
                                   '</div>'); 
          }
          image_holder.show();
          reader.readAsDataURL($(this)[0].files[i]);
        }
      } else {
        alert("O browser não suporta upload de arquivos.");
      }
    } else {
      alert("Formato de arquivo inválido");
    }
  });

  $(midiaDigital).on("click",".remove_field1", function(e){ //user click on remove text
    e.preventDefault(); $(this).parent('div').remove(); 
    img.val = '';
    input.value = null;
    console.log('Input value after remove: ', input.value)
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="midiasUpload" multiple="multiple" type="file" name="midias" accept="image/x-png,image/gif,image/jpeg" /> 
<div id="midiaDigital" style="margin-bottom: 100px;"></div>

Sign up to request clarification or add additional context in comments.

7 Comments

Thanks for your help, but when I click, all of files are removed from file input. I would like to remove only the specific file that I've clicked in remove.
@MuriloGóesdeAlmeida, I have updated the answer, now it should work as you expected
Even here in "run code snippet", appears the Error: { "message": "Uncaught TypeError: img.val is not a function", "filename": "stacksnippets.net/js", "lineno": 61, "colno": 9 }
I've tried in my code and the error is the same: img.val is not a function
This doesn't actually remove the selected file from the file input element, it just (attempts to) removes the preview image. If they submit the upload, the 'removed' file will still be uploaded.
|
-1

Please change this code inside $(image_holder).append( function

'<a href="#" data-id="'+i+'" class="remove_field1">Remover</a>' + //add input box

This code works after clicking on remove_field1

$(midiaDigital).on("click",".remove_field1", function(e){ //user click on remove text
    e.preventDefault(); $(this).parent('div').remove(); 
    var deletedId=$(this).prop("data-id");
    var names = [];
    for (var i = 0; i < $("#midiasUpload").get(0).files.length; ++i) {
     if(deletedId==i){}else{  names.push($("#midiasUpload").get(0).files[i].name);  }
    }
    $("#midiasUpload").val(names);
}); 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.