JJ BOBO JJ BOBO - 1 year ago 72
Javascript Question

Not Able to Target Closest img Element To File Input Element

Can you please take a look at this snippet and let me know why I am not able to target the closest image element to file input



$('.file').on('change', function(ev) {
var f = ev.target.files[0];
var fr = new FileReader();
fr.onload = function(ev2) {
$(this).closest('.img').attr('src', ev2.target.result);
$(this).find('.img').attr('src', ev2.target.result);
$(this).next('.img').attr('src', ev2.target.result);
};
fr.readAsDataURL(f);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="file" class="file" name="image" />
<img class="img" />
<input type="file" class="file" name="image" />
<img class="img" />





As you can see I already tried

$(this).closest('.img').attr('src', ev2.target.result);
$(this).find('.img').attr('src', ev2.target.result);
$(this).next('.img').attr('src', ev2.target.result);


but it is not doing the job

Dij Dij
Answer Source

you have to find img closest to the input file which changes, so you must use ev.target because inside the second function scope changes and this does not refer to file input anymore, something like this seems to work:

$('.file').on('change', function(ev) {
   var f = ev.target.files[0];
   var fr = new FileReader();
   fr.onload = function(ev2) {
     $(ev.target).next('.img').attr('src', ev2.target.result);
   };
   fr.readAsDataURL(f);
 });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="file" class="file" name="image" />
<img class="img" />
<input type="file" class="file" name="image" />
<img class="img" />

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download