lost9123193 lost9123193 - 2 months ago 6
Javascript Question

Accessing Undefined Value in Javascript

I'm having some problems in tackling this.

A user can upload an image to a variable called photo_id in my form. I take the first file object in photo_id and send it to the database to create a file object.

if (photo_id) {
var file=photo_id[0]
//send to database and set id to new object created
}


However, sometimes, a user will click the file upload button but not add a file. A fileList object is still made and put into the photo_id variable but it has a length of 0, which makes it undefined.

enter image description here

In this scenario, when I run this:

if (photo_id ) {
var file=photo_id[0]
....
}


I get

Cannot read property '0' of undefined


I need to check to make sure the FileList length is greater than 0 but even when I do this:

if (photo_id[0].length >0) {
var file=photo_id[0]
//send to database and set id to new object created
}


I get the error:

cannot read length of undefined


How can I check for both scenarios where the FileList exist and it's length is >0?

Answer

You are checking the length of the first element, but there is no first element. Use:

if (photo_id && photo_id.length > 0) {...}
Comments