Search code examples
javascriptjquerypreview

Preview an many image before it is uploaded


For the first input it works well, but not for the second. Instead of updating the second one it updates the first. How do I separate this two input previews with the same function?

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

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

    reader.readAsDataURL(input.files[0]); // convert to base64 string
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="file" onchange="readURL(this);" required>
<img id="load" src="../img/preview.png" alt="loading" width=50 height=50>

<input type="file" onchange="readURL(this);" required>
<img id="load" src="../img/preview.png" alt="loading" width=50 height=50>


Solution

  • Firstly, the IDs should be unieque, so set "load" to "load1" and "load2" for the img element.
    And you should distinguish the output target by the input.
    $('#blah').attr('src', e.target.result); always updates the element '#blah'.
    Therefore, add an argument to the readURL() that specifies the output destination, and modify it to update there.

        function readURL(input, target) {
          if (input.files && input.files[0]) {
            var reader = new FileReader();
        
            reader.onload = function(e) {
              $(target).attr('src', e.target.result);
            }
        
            reader.readAsDataURL(input.files[0]); // convert to base64 string
          }
        }
    
        <input type="file" onchange="readURL(this, '#load1');" required>
        <img id="load1" src="../img/preview.png" alt="loading" width=50 height=50>
        
        <input type="file" onchange="readURL(this, '#load2');" required>
        <img id="load2" src="../img/preview.png" alt="loading" width=50 height=50>