Trying to get multiple file inputs and their corresponding previews to load. I am getting elements by classname but i don't think i'm iterating over them correctly. I don't want to use unique IDs for the elements since i will be adding these to the page dynamically and can't hardcode unique IDs for each input. If you could please edit my code or tell me what i'm doing wrong. Thanks. Codepen below. https://codepen.io/pfbarnet/pen/VwMgmbP
var fileTag = document.getElementsByClassName("filetag"), i,
preview = document.getElementsByClassName("preview"), i;
for (i = 0; i < fileTag.length; ++i) {
//check if fileTag null
fileTag[0].addEventListener("change", function () {
changeImage(this);
});
function changeImage(input) {
var reader;
if (input.files && input.files) {
reader = new FileReader();
reader.onload = function (e) {
preview[0].setAttribute("src", e.target.result);
};
}
reader.readAsDataURL(input.files[0]);
}
}
<input type='file' class='filetag'><img src='test' class='preview'/></input>
<input type='file' class='filetag'><img src='test' class='preview'/></input>
Few notec my friend. First you need to declare your variable i inside the loop with a let keyword, otherwise it will be global scoped.
In your loop, instead of always assigning event listener to the first element you need to make it dynamic by writing fileTag[i] instead of fileTag[0]
Also when changeImage is being called, also pass the i variable to it, so inside the body of this function, you can change exact image's src.
Take a look at the code below.
for (let i = 0; i < fileTag.length; ++i) { // <- Declare with a let keyword
fileTag[i].addEventListener("change", function () {
changeImage(this, i); // <- HERE
});
}
And here, use i to indicate which exact element you are mutating e.g. the image and the fileInput
function changeImage(input, i) {
console.log(input);
var reader;
if (input.files && input.files) {
reader = new FileReader();
reader.onload = function (e) {
preview[i].setAttribute("src", e.target.result);
};
}
reader.readAsDataURL(input.files[i]);
}