I want to use jquery function multiple times with different ID’s to upload different images. For example if I use input field with id=myImg1 for upload an image, it should’t upload this image for input field with id=myImg=2, but it does so. I want to try something like for loop, but don’t understand how to do it.
I’ve tried this code:
$(function() {
$(":file").change(function() {
if (this.files && this.files[0]) {
for (var i = 0; i < this.files.length; i++) {
var reader = new FileReader();
reader.onload = imageIsLoaded;
reader.readAsDataURL(this.files[i]);
}
}
});
});
function imageIsLoaded(e) {
$('div[id^=myImg]').append('<img src=' + e.target.result + '>');
};
<input type="file" multiple/>
<div id="myImg1"></div>
<p>Геоморфология</p>
<input type="text" placeholder="" name="place" class="input"/><br>
<input type="file" multiple/>
<div id="myImg2"></div>
This results in
this
3
Answers
It’s because you should append into the needed div, instead of appending into all the
div
‘sIn my example I am passing the extra
data-id
attr to the input and based on that I am identifying to which div should I append the current image.You can simplify your code…
by replacing FileReader with URL.createObjectURL. This allows you to append the images in one step:
And adding the accept attribute to the file inputs will make it easier for users to select only images.
Your problem is solved with jQuery.next which appends the images to the next matching id:
Combining these changes we get this snippet:
Since the DIV is always the next element after the file input, use
$(this).next()
to select it, rather than selecting by ID.