Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5 FileList and JQuery's each

I grab the filelist ([http://www.w3.org/TR/FileAPI/#dfn-filelist]) and then I want to use JQuery's each function.

var file_list = $(this).attr('files');
/* Code goes here */
file_list.each(function()
{
/* Code goes here */

I get the following error:

Uncaught TypeError: Object #<FileList> has no method 'each'

Any idea? Thank you.

like image 296
thom Avatar asked Mar 15 '11 14:03

thom


People also ask

How do I loop a FileList?

One way to let us loop through each item in a file list object is to convert it to an array with the Array. from method. Then we can use the forEach method on it to loop through the file list entries. The file input has the multiple attribute so that we can select multiple files.

Is FileList an array?

FileList is an object which represents an array of individually selected files from the underlying system.

Which content is shown by file list?

The File List component displays a list of multiple folders and files by using the file/folder name, an icon, and other properties that you specify.


2 Answers

It is because $(this).attr('files'); just returns the plain DOM file list, and not a jQuery object.

Either you need to loop over it the old fashioned way:

for(var i=0,file;file=file_list[i];i++) {
 //do your thing
}

or you could use $.each:

$.each(file_list,function(idx,elm){
     //do your thing
});

Be aware that $.each is slower than the plain for loop, and in this case gives you very little convenience, so i'd stick with the for loop.

like image 134
Martin Jespersen Avatar answered Oct 24 '22 19:10

Martin Jespersen


var file_list = $(this).attr('files');
$.each(file_list,function(i,item){
  // i is the index (integer) of current item
  // item is the current item
  // $(this) is the jQuery selector for the current item
});
like image 21
Teddy Avatar answered Oct 24 '22 20:10

Teddy