How to reset an input type="file"?

1

I have the following code:

$(function() {
  // Multiple images preview in browser
  var imagesPreview = function(input, placeToInsertImagePreview) {

    if (input.files) {
      var filesAmount = input.files.length;
      $(placeToInsertImagePreview).empty(); // remove as imagens antigas
      for (i = 0; i < filesAmount; i++) {
        var reader = new FileReader();

        reader.onload = function(event) {
          $($.parseHTML('<img>')).attr('src', event.target.result)
            .appendTo(placeToInsertImagePreview);
        }

        reader.readAsDataURL(input.files[i]);
      }
    }

  };

  $('#gallery-photo-add').on('change', function() {
    imagesPreview(this, 'div.gallery');
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputtype="file" multiple id="gallery-photo-add">
<div class="gallery"></div>

I would like to see a button for clear ONLY of input ?

    
asked by anonymous 15.10.2017 / 00:20

1 answer

1
To clean the contents of a input type file use with :

document.getElementById("id_do_elemento").value = ''

or :

$("id_do_elemento").val('');

From your minimal example, the button functionality has been added by appearing with the number of photos greater than zero and clicking the button again, minimum example strong>:

$(function() {
  $("#BtnLimpar").hide();
  var imagesPreview = function(input, placeToInsertImagePreview) {

    if (input.files) {
      var filesAmount = input.files.length;
      if (filesAmount > 0) $("#BtnLimpar").show();
      $(placeToInsertImagePreview).empty(); // remove as imagens antigas
      for (i = 0; i < filesAmount; i++) {
        var reader = new FileReader();
        reader.onload = function(event) {
          $($.parseHTML('<img>')).attr('src', event.target.result)
            .appendTo(placeToInsertImagePreview);
        }
        reader.readAsDataURL(input.files[i]);
      }
    }
  };
  $('#gallery-photo-add').on('change', function() {
    imagesPreview(this, 'div.gallery');
  });
  $("#BtnLimpar").on('click', function(){
      $('#gallery-photo-add').val('');
      $(this).hide();
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"> 
</script>
<div><input type="file" multiple id="gallery-photo-add"></div>
<div><button id="BtnLimpar">Limpar</button></div>
<div class="gallery"></div>
    
15.10.2017 / 00:36