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?

2 Answers 2

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);
Sign up to request clarification or add additional context in comments.

Comments

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.