1

Tenho o seguinte código:

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

e gostaria que após a exibição das imagens aparecesse também um botão para limpar SOMENTE o input de files?

1 Resposta 1

3

Para limpar o conteúdo de um input type file use com :

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

ou com :

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

A partir do seu exemplo minimo, foi adicionado a funcionalidade do botão aparecer mediante a quantidade de fotos maior do que zero e ao clicar no botão esconder novamente o botão, exemplo minimo:

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

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .