title: Javascript - Image preview before upload. Needed on multiple instances on same page
body: <p>I have a page that has multiple fields to upload images individually and I wanted a script that would allow the user to preview the image before submitting.</p>
  
  <p>I used this script on the first field and it works fine.</p>
  
  <pre><code>&lt;script type="text/javascript"&gt;
      function readURL(input) {
          if (input.files &amp;&amp; input.files[0]) {
              var reader = new FileReader();
  
              reader.onload = function (e) {
                  $('#main').attr('src', e.target.result);
              }
  
              reader.readAsDataURL(input.files[0]);
          }
      }
  &lt;/script&gt;
  </code></pre>
  
  <p>However, it doesn't work for the remainder of the previews even if I make them unique. What should I do in order to copy the same script and have it work on multiple instances on the same page?</p>
  
  <p>Update:</p>
  
  <p>The html for the preview looks like this:</p>
  
  <pre><code>                    &lt;div class="row"&gt;
                          &lt;div class="col-md-3"&gt;
                              &lt;h5&gt;Main Photo:&lt;/h5&gt;
                              &lt;input class="form-control" type="file" name="main" onchange="readURL(this);" /&gt;
                          &lt;/div&gt;
                          &lt;div class="col-md-3"&gt;
                              &lt;h6&gt;Preview:&lt;/h6&gt;
                              &lt;img id='main' style="height:100px;" /&gt;
                          &lt;/div&gt;
                          &lt;div class="col-md-3"&gt;
                              &lt;h5&gt;Front Photo:&lt;/h5&gt;
                              &lt;input class="form-control" type="file" name="front" onchange="readURL(this);" /&gt;
                          &lt;/div&gt;
                          &lt;div class="col-md-3"&gt;
                              &lt;h6&gt;Preview:&lt;/h6&gt;
                              &lt;img id='front' style="height:100px;" /&gt;
                          &lt;/div&gt;
                      &lt;/div&gt;
  </code></pre>