0

I am using this code in my image uploader:

Html:

<input type="file" id="files" name="files[]" multiple />
<ul id="list"></ul>

JS:

function handleFileSelect(evt) {
var files = evt.target.files; // FileList object

for (var i = 0, f; f = files[i]; i++) {

  if (!f.type.match('image.*')) {
    continue;
  }

  var reader = new FileReader();

  reader.onload = (function(theFile) {
    return function(e) {
      var li = document.createElement('li');
      li.innerHTML = ['<img class="thumb" src="', e.target.result,
                        '" title="', escape(theFile.name), '"/><input type="text" class="rename" name="',i,'" value="',escape(theFile.name),'"><input type="text" class="reorder" name="',i,'" value="',i,'">'].join('');
      document.getElementById('list').insertBefore(li, null);
    };
  })(f);

  reader.readAsDataURL(f);
}
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);

My problem is when it gets to reader.onload, the for loop is done so i = #of images not image # like I want it to be. Is there any way to fix this so the name of my inputs is the image # of the image they're next to?

Marcel
  • 1,034
  • 1
  • 17
  • 35

2 Answers2

1

reader.onload runs as many times as there are pictures being uploaded.

var x = 0;
  reader.onload = (function(theFile) {
    return function(e) {

      console.log(x);

      x++;

    };
  })(f);
Marcel
  • 1,034
  • 1
  • 17
  • 35
1

You already have a solution for f. You could just do exactly the same thing for i: pass it to the handler's closure:

  reader.onload = (function(theFile, i) {
    return function(e) {
      var li = document.createElement('li');
      li.innerHTML = ['<img class="thumb" src="', e.target.result,
                        '" title="', escape(theFile.name), '"/><input type="text" class="rename" name="',i,'" value="',escape(theFile.name),'"><input type="text" class="reorder" name="',i,'" value="',i,'">'].join('');
      document.getElementById('list').insertBefore(li, null);
    };
  })(f, i);
blgt
  • 8,135
  • 1
  • 25
  • 28