How can I implement this code into a loop for 20 files? They will have id="myFile1", "myFile2" etc.
<script type="text/javascript">
var myFile = document.getElementById('myFile');
myFile.addEventListener('change', function() {
alert(this.files[0].size);
});
</script>
My first idea was to do 20 scripts, but I don' really think that it would be good solution, I really prefer clean code.
I tried this... but doesn't work for some reason - the second file reports "NaN" instead of file size in bytes.
<script type="text/javascript">
var myFile = document.getElementById('myFile');
myFile.addEventListener('change', function() {
var totalSize = this.files[0].size;
alert(totalSize);
});
</script>
<script type="text/javascript">
var myFile1 = document.getElementById('myFile1');
myFile1.addEventListener('change', function() {
var totalSize = totalSize + this.files[0].size;
alert(totalSize);
});
</script>
I would also like to implement an IF conditional that would alert only if the totalSize were bigger than 7 MB, that means that I need the totalSize/(1024*1024) - easy to do, but not the loop .
Could you please help me building a working loop that would count the totalSize of all the files? myFile is an ID of input type="file" element.
2 Answers 2
Try and use following logic:
<script type="text/javascript">
var totalSize=0;
function checkSize() {
totalSize = totalSize + this.files[0].size;
alert(totalSize); //write logic to check size validation etc. here
}
for(var i=1;i<=20;i++)
{
var myFile = document.getElementById('myFile'+i);
myFile.addEventListener('change',checkSize);
}
</script>
Comments
I don't know if I understood correctly what you need, but this could be your case: http://jsbin.com/ozadak/2/edit
CODE
var totArray = [];
for (var x = 1; x <= 5; x++) {
var currFile = document.getElementById("myFile"+x);
currFile.addEventListener('change', function(x){
totArray[this.id] = parseInt(document.getElementById(this.id).value); //here goes file.size
var currTot = 0;
for(var key in totArray){
currTot += totArray[key];
}
if(currTot > 10)
alert("file sizes > 10 MB");
});
}
for simplicity I used some text input, to show how the loop works adding each input the same event. To test it, input an integer representing how many MB does your file weight, it should work.
Hope it helps, regards