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.
- JavaScript closure inside loops – simple practical example
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures - function PreviewImage() { var funcs = []; var documentos = document.getElementById("uploadImage"); var tamanio = documentos.files.length; for (var i = 0; i < tamanio; i++) { funcs[i] = (function(index) { return function(event) { document.getElementById("uploadPreview" + index).src = event.target.result; }; })(i); } var oFReader = new FileReader(); for (var k = 0; k < tamanio; k++) { oFReader = new FileReader(); oFReader.readAsDataURL(documentos.files[k]); oFReader.onload = funcs[k];
 }
 }
Thank you
 
    