Skip to content
Advertisement

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 videoUploadFile, check if it’s empty, throw an error message if it’s empty?

Advertisement

Answer

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");
}
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement