user3753569 user3753569 - 5 months ago 33
jQuery Question

How to check if input file is empty in JQuery

Brand new to JS.

I am trying to check if the file input element is empty when submitting the form with jquery/javascript.
I have gone through a bunch of solutions and nothing is working for me. I am trying to avoid the /c/fakepath (unless there is no other option)

<input type="file" name="videoFile" id="videoUploadFile" />

this does not work:

var vidFile = $("#videoUploadFile").value;

the only way I can get the filename is if I use the following:

var vidFile = document.getElementById("videoUploadFile").files[0].name;

If there is no file available the code throws an error:
cannot read property name of undefined

which makes sense because the array is not set. but I cannot figure out how to do any error handling with this.

How do I properly grab the file input element
, check if it's empty, throw an error message if it's empty?


Just check the length of files property, which is a FileList object contained on the input element

if( document.getElementById("videoUploadFile").files.length == 0 ){
    console.log("no files selected");