Nemanja G
Nemanja G

Reputation: 1850

Preview Different images on HTML Form

I have an HTML form with multiple inputs for uploading pics. I need to preview each of those pics after I click Choose File button:

$(function() {
  $("#img1").change(function() {
    if (this.files && this.files[0]) {
      var reader = new FileReader();
      reader.onload = imageIsLoaded;
      reader.readAsDataURL(this.files[0]);
    }
  });
});

function imageIsLoaded(e) {
  $('#myImg1').attr('src', e.target.result);
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td> <input id="img1" name="img1" type="file" /> </td>
    <td> <img id="myImg1" src="#" alt="your image" /> </td>
  </tr>
  <tr>
    <td> <input id="img2" name="img2" type="file" /> </td>
    <td> <img id="myImg2" src="#" alt="your image" /> </td>
  </tr>
  <tr>
    <td> <input id="img3" name="img3" type="file" /> </td>
    <td> <img id="myImg3" src="#" alt="your image" /> </td>
  </tr>
</table>

Thanks in advance!

Upvotes: 2

Views: 53

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337560

To achieve this you can place common classes on all the file inputs and img elements. From there you can use DOM traversal to find the img related to the input and update it's src attribute when a file is selected. Try this:

$(function() {
  $('.img').change(function() {
    if (this.files && this.files[0]) {
      var $view = $(this).closest('tr').find('.view');
      var reader = new FileReader();
      reader.onload = function(e) {
        $view.attr('src', e.target.result);
      }
      reader.readAsDataURL(this.files[0]);
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td><input id="img1" name="img1" type="file" class="img" /> </td>
    <td><img id="myImg1" src="#" alt="your image" class="view" /> </td>
  </tr>
  <tr>
    <td><input id="img2" name="img2" type="file" class="img" /> </td>
    <td><img id="myImg2" src="#" alt="your image" class="view" /> </td>
  </tr>
  <tr>
    <td><input id="img3" name="img3" type="file" class="img" /> </td>
    <td><img id="myImg3" src="#" alt="your image" class="view" /> </td>
  </tr>
</table>

Upvotes: 2

Related Questions