Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

231
Visualizações
JS multiple file input elements on page - inputs not working past first input (preview image not showing)

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>
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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]);
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda