I'm currently getting to grips with html5 API image uploading and I'm a bit stuck with some javascript (way out my comfort zone) involved.
This is a snippet of my upload table (it also involves data collection for each image not shown here for things like renaming the image etc):
<tr>
<td>Image '.$i.':</td><td><output id="display'.$i.'"></output></td>
</tr>
<tr>
<td>Choose Image:</td>
<td><input name="file'.$i.'" type="file" id="file'.$i.'" accept="image/*" /></td>
</tr>
$i
is a php counter, the user selects how many photos they will upload and it creates that many image boxes.
This is the javascript used to show an image preview:
document.getElementById('file1').addEventListener('change', handleFileSelect, false);
function handleFileSelect(evt) {
var files = evt.target.files;
var f = files[0];
var reader = new FileReader();
reader.onload = (function(theFile) {
return function(e) {
document.getElementById('display1').innerHTML = ['<img src="', e.target.result,'" title="', theFile.name, '" width="100" />'].join('');
};
})(f);
reader.readAsDataURL(f);
}
My question is, being a javascript novice, is there a simple way to loop the script for each image. Currently it will only show the preview for 'file1', is there a way to change the '1' to something like $i, $i++
used for php loops? lets say the number of image boxes is stored as the php varible $totelboxes
EDIT: this is where I am so far:
var upFiles = document.getElementsByClassName('upFile');
for(var i = 0; i < upFiles.length; i++)
{
upFiles[i].addEventListener('change', handleFileSelect, false);
function handleFileSelect(evt) {
var files = evt.target.files;
var f = files[0];
var reader = new FileReader();
reader.onload = (function(theFile) {
return function(e) {
document.getElementById('display'+i).innerHTML = ['<img src="', e.target.result,'" title="', theFile.name, '" width="100" />'].join('');
};
})(f);
reader.readAsDataURL(f);
}
}