1

I'm trying to build a image preview for uploaded files but i want the images to update their previews when user re-uploades on the same input. The code that i wrote for multiple images works but the one with primary image doesn't.

$(function() {

  // Multiple images preview in browser
  var imagesPreview = function(input, placeToInsertImagePreview, type) {
    if (type === 'multiple') {
      if ($('#gallery').children().length > 1) {
        $('#gallery').children().slice(1).remove();
      }
    } else if (type === 'primary') {
      $('#primary').empty();
    }

    if (input.files) {
      var filesAmount = input.files.length;

      for (i = 0; i < filesAmount; i++) {
        var reader = new FileReader();

        reader.onload = function(event) {
          $($.parseHTML('<img>')).attr('src', event.target.result).appendTo(placeToInsertImagePreview).addClass('col rounded upload-img shadow-sm');

        }

        reader.readAsDataURL(input.files[i]);
      }
    }
    var $fileUpload = $("input[type='file']");
    if (parseInt($fileUpload.get(0).files.length) > 2) {
      alert("You can only upload a maximum of 2 files");
    }
  };

  $('#gallery-photo-add').on('change', function() {
    imagesPreview(this, 'div.gallery', 'multiple');
  });
  $('#primary').on('change', function() {
    imagesPreview(this, 'div.primary', 'primary');
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="file" name="image[]" multiple id="gallery-photo-add">
<div class="card primary" id="primary"></div>
<div class="gallery row" id="gallery"></div>

I tried to console log inside

          }else if (type === 'primary') {
              $('#primary').empty();
              console.log('deleted');
          }

It displays deleted but does nothing. Also i've tried something like this too

          }else if (type === 'primary') {
              $('#primary').children().remove();
          }

Still no luck. What am i missing?

Here's the full inputs

            <div class="form-group">
                <div class="input-group">
                    <div class="input-group-prepend">
                        <span class="input-group-text" id="inputGroupFileAddon01">@lang('product.upload')</span>
                    </div>
                    <div class="custom-file">
                        <input type="file" class="custom-file-input" id="primary" name="primaryimg" aria-describedby="primary">
                        <label class="custom-file-label" for="primaryimg">Choose file</label>
                    </div>
                </div>
                <input type="file" name="image[]" multiple id="gallery-photo-add">
                <div class="card primary" id="primary"></div>
                <div class="gallery row" id="gallery"></div>
            </div>
            <button type="submit" class="btn btn-primary">Submit</button>
Areg
  • 1,414
  • 1
  • 19
  • 39

2 Answers2

3

You can use files on the input to get the length:

var filesCount = $(this)[0].files.length;

$(function() {

  // Multiple images preview in browser
  var imagesPreview = function(input, placeToInsertImagePreview, type) {
    if (type === 'multiple') {
      if ($('#gallery').children().length > 1) {
        $('#gallery').children().slice(1).remove();
      }
    } else if (type === 'primary') {
      $('#primary').empty();
    }

    if (input.files) {
      var filesAmount = input.files.length;

      for (i = 0; i < filesAmount; i++) {
        var reader = new FileReader();

        reader.onload = function(event) {
          $($.parseHTML('<img>')).attr('src', event.target.result).appendTo(placeToInsertImagePreview).addClass('col rounded upload-img shadow-sm');

        }

        reader.readAsDataURL(input.files[i]);
      }
    }
    var $fileUpload = $("input[type='file']");
    if (parseInt($fileUpload.get(0).files.length) > 2) {
      alert("You can only upload a maximum of 2 files");
    }
  };

  $('#gallery-photo-add').on('change', function() {
    var filesCount = $(this)[0].files.length;
    console.log(filesCount);
    imagesPreview(this, 'div.gallery', 'multiple');
  });
  $('#primary').on('change', function() {
    imagesPreview(this, 'div.primary', 'primary');
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="file" name="image[]" multiple id="gallery-photo-add">
<div class="card primary" id="primary"></div>
<div class="gallery row" id="gallery"></div>
designtocode
  • 2,215
  • 4
  • 21
  • 35
0

As per the edit you have posted, there are two DOM elements with the same id primary(file element and a div). But at no particular instance a DOM should be having two elements with the same ids. So if you want your single file upload to work like the same as multiple files, use a different id for the div that you need to empty.Like

<div class="card primary" id="singlefile"></div>

You can empty this div by targeting the id like

}else if (type === 'primary') {
          $('#singlefile').empty();
          console.log('deleted');
      }

Hope this helps.

Krishna Prashatt
  • 631
  • 9
  • 18