0

I've got the next code:

            function PreviewImage() {
            var oFReader = new FileReader();
            var documentos = document.getElementById("uploadImage");
            var tamanio = documentos.files.length;
            for (var i = 0; i < tamanio; i++) {
                document.write("-"+i);
                oFReader = new FileReader();
                oFReader.readAsDataURL(documentos.files[i]);
                oFReader.onload = function(event) {
                    document.write("+"+i);
                    document.getElementById("uploadPreview"+i).src = event.target.result;
                };                   
            }          
        }

This read the files from the input uploadImage. I want to preview the images on tags which id="uploadPreviewX". It works great when I don't use for loop. I printed "i" for testing, the first impression is correct: -0-1-2 - ... - (tamanio-1), the problem is the second, then prints tamanio tamanio times. For example, if you select 4 files the output is: -0-1-2-3 +4 +4 +4 +4. And therefore I can only preview a img where id = uploadPreview4. What am I doing wrong?

UPDATE SOLVE After reading some documentation about Javascript closure inside loops... I could do it.

Thank you

Community
  • 1
  • 1
SerchRac
  • 171
  • 1
  • 12

0 Answers0