Reputation: 59
How can I write the code below as a jquery:
var imagefile = document.getElementsByClassName("fileImage");
var filename = imagefile.files[0];
I attempted this below but it says it is not defined even though I have already stated file input's class is 'fileImage'.
var filename = $('.fileImage').files[0];
Upvotes: 1
Views: 134
Reputation: 150030
The jQuery object returned by the $() function doesn't have a .files property - that property belongs to the DOM element. Try this:
var filename = $('.fileImage')[0].files[0];
This will still give an error if no elements match the selector, otherwise it uses the square-bracket array syntax on the jQuery object to get a reference to the first matching element.
If you want to test if any elements matched the selector use the jQuery objects .length property:
var $files = $('.fileImage'),
filename;
if ($files.length > 0) {
filename = $files[0].files[0];
// do something with filename...
}
Upvotes: 3
Reputation: 119847
you can't directly do imagefile.files[0]
since
document.getElementsByClassName("fileImage")
//and
$('.fileImage')
return an "array-like" list of items. (AFAIK, getElementsBy*
functions, except for getElementsById
, return a NodeList
)
you need to iterate through them first, before you get files[0]
.
for the pure JS approach:
for(var i=0; i < imagefile.length;i++){
var imgfile = imagefile[i];
//now imgfile is the DOM element itself
imgfile.files[0];
}
for the jQuery, you chain .each()
$('.fileImage').each(function(){
//"this" in here is the DOM element
this.files[0];
})
Upvotes: 4