How to reset an input type="file"?

Asked

Viewed 2,487 times

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>
<input type="file" multiple id="gallery-photo-add">
<div class="gallery"></div>

and I would like that after the display of the images also appear a button to clean up ONLY the input of files?

1 answer

2


To clear the contents of a input type file use with :

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

or with :

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

From your minimum example, was added the functionality of the button appear by the amount of photos greater than zero and by clicking the hide button again, minimal example:

$(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>

<script src="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>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.