Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

243
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda