thom thom - 4 months ago 44
HTML Question

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.

Answer

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.