如何检查jQuery中的输入文件是否为空 [英] How to check if input file is empty in jQuery

查看:163
本文介绍了如何检查jQuery中的输入文件是否为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

全新的JS。

我试图检查在使用jQuery / JavaScript提交表单时文件input元素是否为空。
我已经经历了一堆解决方案,没有任何工作适合我。我试图避免使用 / c / fakepath (除非没有其他选项)

 < input type =filename =videoFileid =videoUploadFile/> 

这不起作用:

  var vidFile = $(#videoUploadFile)。value; 

我可以得到文件名的唯一方法是使用以下内容:

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

如果没有可用的文件,代码会抛出错误:


无法读取未定义的属性名称

这很有意义,因为数组不是组。但我无法弄清楚如何处理任何错误。



如何正确抓取文件输入元素 videoUploadFile ,检查它是否为空,如果它是空的,会抛出一个错误信息? 只要检查文件属性,它是 FileList 对象包含在输入元素中

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


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?

解决方案

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");
}

这篇关于如何检查jQuery中的输入文件是否为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆