priwebdev priwebdev - 6 months ago 24
Javascript Question

jQuery function for more than one image preview before upload

I'm using more than one

<input type="file">
tag in my page with same class="inputFile" as shown below

<div class="col-md-3">
<form id="form2" runat="server">
<input type='file' class="inputFile" />
<img class="image_upload_preview" src="http://placehold.it/100x100" alt="your image" />
</form>
</div>
<div class="col-md-3">
<form id="form3" runat="server">
<input type='file' class="inputFile" />
<img class="image_upload_preview" src="http://placehold.it/100x100" alt="your image" />
</form>
</div>


I want to show the preview of the image when I select an image, and I'm using jQuery function for that.

function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
$('.image_upload_preview').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$(".inputFile").change(function() {
readURL(this);
});


This code is working fine, but when I'm choosing an image for the first tag, it is selecting the same image for both fields as below:

enter image description here

How can I solve this?

Answer

You just need to amend your readURL function to traverse the DOM to find the .image_upload_preview element related to the current input. Try this:

function readURL(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();
        reader.onload = function(e) {
            $(input).next('.image_upload_preview').attr('src', e.target.result);
        }
        reader.readAsDataURL(input.files[0]);
    }
}

$(".inputFile").change(function() {
    readURL(this);
});

Note the use of $(input).next('.image_upload_preview').