title: Reuse java script function to Show Multiple Images Preview
body: <p><a href="https://i.stack.imgur.com/AQNNO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/AQNNO.png" alt="enter image description here"></a></p>
  
  <p>Hello!</p>
  
  <p>I wrote the single java script function to show the image preview before uploading.
  For single file uploading, my code is working fine.</p>
  
  <p>But now i want to give multiple image uploading options by giving multiple select options to user(see the snapshot). Also for this, i want to reuse my function that is displaying the preview of selected first image.(see the image in snapshot)</p>
  
  <p>How would i modify my html code and how to reuse my script function?</p>
  
  <p>html</p>
  
  <pre><code>&lt;form action="upload.php" method="post" enctype="multipart/form-data"&gt;
      &lt;div id="wrapper" style="margin-top: 20px;"&gt;
      &lt;input id="fileUpload"  name="uploadedFile" type="file"/&gt; 
      &lt;input  id="fileUpload2"  name="" type="file"/&gt; 
      &lt;input id="fileUpload3"  name="uploadedFile" type="file"/&gt; 
      &lt;div id="image-holder"&gt;&lt;/div&gt;
  
  &lt;/div&gt;
  &lt;/form&gt;
  </code></pre>
  
  <p>Javascript</p>
  
  <pre><code>&lt;script&gt;
  $(document).ready(function() {
          $("#fileUpload").on('change', function() {
            //Get count of selected files
            var countFiles = $(this)[0].files.length;
            var imgPath = $(this)[0].value;
            var extn = imgPath.substring(imgPath.lastIndexOf('.') + 1).toLowerCase();
            var image_holder = $("#image-holder");
            image_holder.empty();
            if (extn == "gif" || extn == "png" || extn == "jpg" || extn == "jpeg") {
              if (typeof(FileReader) != "undefined") {
                //loop for each file selected for uploaded.
                for (var i = 0; i &lt; countFiles; i++) 
                {
                  var reader = new FileReader();
                  reader.onload = function(e) {
                    $("&lt;img /&gt;", {
                      "src": e.target.result,
                      "class": "thumb-image"
                    }).appendTo(image_holder);
                  }
                  image_holder.show();
                  reader.readAsDataURL($(this)[0].files[i]);
                }
              } else {
                alert("This browser does not support FileReader.");
              }
            } else {
              alert("Pls select only images");
            }
          });
        });
  &lt;/script&gt;
  </code></pre>