Preview image with jquery, multiple separate images input

Viewed 23

I have this problem, I have three input field on a div, I want to add a preview when the file input field is changed.

The code only works for the first input, if you select an image in logo-2, or logo-3, it will update the preview for logo-1

Works: The problem was from design, the field field is hidden and i using two labels [text, and image] to trigger them, updated the for="" for only the text label but i was using image as trigger, hence only the first one was working as they all had the same for=""

$("input[type='file']").change(function(e) {
  var target_id = '#' + $(this).data('preview');
  $(target_id).attr('src', URL.createObjectURL(e.target.files[0]));
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<div>
  <label for="logo-1">Logo 1 </lable>
    <img id="logo-1-preview"src="logo-1.png" alt="">
    <input type="file" accept="image/*" name="logo-1" data-preview="logo-1-preview">
</div>
<div>
    <label for="logo-2">Logo 2 </lable>
    <img id="logo-2-preview"src="logo-2.png" alt="">
    <input type="file" accept="image/*" name="logo-2" data-preview="logo-2-preview">
</div>
<div>
    <label for="logo-3">Logo 3 </lable>
    <img id="logo-3-preview"src="logo-3.png" alt="">
    <input type="file" accept="image/*" name="logo-3" data-preview="logo-3-preview">
</div>

1 Answers

It update the right img tag for each input (check with console), you just need css to separate things

$("input[type='file']").change(function(e){
    var target_id = '#' + $(this).data('preview');
    $(target_id).attr('src', URL.createObjectURL(e.target.files[0]));        
})
img { max-width: 200px; }
div { width:100%; display:inline-block; padding: 15px; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
    <label for="logo-1">Logo 1 </lable>
    <img id="logo-1-preview"src="logo-1.png" alt="">
    <input type="file" accept="image/*" name="logo-1" data-preview="logo-1-preview">
</div>
<div>
    <label for="logo-2">Logo 2 </lable>
    <img id="logo-2-preview"src="logo-2.png" alt="">
    <input type="file" accept="image/*" name="logo-2" data-preview="logo-2-preview">
</div>
<div>
    <label for="logo-3">Logo 3 </lable>
    <img id="logo-3-preview"src="logo-3.png" alt="">
    <input type="file" accept="image/*" name="logo-3" data-preview="logo-3-preview">
</div>

Related