VipC VipC - 1 month ago 9
HTML Question

How to display multiple thumbnails while uploading images in html using javascript?



function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();

reader.onload = function(e) {
$('#documentUpload')
.attr('src', e.target.result)

};

reader.readAsDataURL(input.files[0]);
}
}

<html>

<head></head>

<body>
<ul>
<li>
<input type='file' onchange="readURL(this);" />
<img id="documentUpload" src="#" alt="first image" />
</li>

<li>
<input type='file' onchange="readURL(this);" />
<img id="documentUpload" src="#" alt="second image" />
</li>
</ul>
</body>

</html>

> Blockquote





" In example , click on any choose image button but image will be displayed in first case only . I changed the id in both case and in javascript as well but it didnt work.
code above is solution to how to display image in html "

Answer

The problem is ID require be unique. In this example, I add an attribute called document-up, and it works. It's possible in this case select more than one element using attributes or classes.

function readURL(input,option) {
  if (input.files && input.files[0]) {
    var reader = new FileReader();

    reader.onload = function(e) {
      if (option == 1){
         $("#documentUpload1")
         .attr('src', e.target.result)
       } else {
         $("#documentUpload2")
        .attr('src', e.target.result)  
       }
    };

    reader.readAsDataURL(input.files[0]);
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<html>

<head></head>

<body>
  <ul>
    <li>
      <input id="input1" type='file' onchange="readURL(this,1);" />
      <img id="documentUpload1" document-up src="#" alt="first image" />
    </li>

    <li>
      <input id="input2" type='file' onchange="readURL(this,2);" />
      <img id="documentUpload2" document-up src="#" alt="second image" />
    </li>
  </ul>
</body>

</html>

Comments