Home > Back-end >  Preview images to a loop html input with jquery in Asp.Net Core?
Preview images to a loop html input with jquery in Asp.Net Core?

Time:11-06

I have a loop in html that creates 4 inputs type of file and inside this loop I have an img tag to preview the selected image...

<div class="gallery_imgproduct">
    @for (int i = 0; i < 4; i  )
    {
    <div class="box_galleryimg col-lg-3 col-md-3 col-sm-6 col-xs-12">
        <div class="form-group">
            <img id="main_image_product" src="~/site/img/product/286289f713.jpg" />
            <input  type="file" asp-for="ProductImgName" onchange="readURL(this);" class="form-control">                
        </div>

    </div>
    }
</div>

The jQuery code below is for preview input only...

 function readURL(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();
        reader.onload = function (e) {
            $('#main_image_product')
                .attr('src', e.target.result)
        };
        reader.readAsDataURL(input.files[0]);
    }
}

I want the preview to be displayed in the img tag if the image is selected... If this is possible, please help. If not, please suggest a solution. Thank you

CodePudding user response:

You have preview image id as "main_image_product" inside for loop. The id must be unique. So you can take that image tag outside the loop or use $i to create unique ids for all preview images.

<img id="main_image_product" src="~/site/img/product/286289f713.jpg" />
<div class="gallery_imgproduct">
  @for (int i = 0; i < 4; i  )
  {
  <div class="box_galleryimg col-lg-3 col-md-3 col-sm-6 col-xs-12">
      <div class="form-group">            
          <input  type="file" asp-for="ProductImgName" onchange="readURL(this);" class="form-control">                
      </div>

  </div>
  }
</div>

OR

<div class="gallery_imgproduct">
  @for (int i = 0; i < 4; i  )
  {
  <div class="box_galleryimg col-lg-3 col-md-3 col-sm-6 col-xs-12">
      <div class="form-group">
          <img id="main_image_product$i" src="~/site/img/product/286289f713.jpg" />
          <input  type="file" asp-for="ProductImgName" onchange="readURL(this,'main_image_product$i');" class="form-control">                
      </div>

  </div>
  }
</div>

    function readURL(input,imgId) {
  if (input.files && input.files[0]) {
      var reader = new FileReader();
      reader.onload = function (e) {
          $('#' imgId)
              .attr('src', e.target.result);
      };
      reader.readAsDataURL(input.files[0]);
  }
} 
  • Related