如何使用JavaScript / jQuery检查输入文件是否为空
给定一个包含输入元素的HTML文档,任务是使用JavaScript检查输入元素是否为空。
方法1
使用 element.files.length 属性来检查文件是否被选中。如果element.files.length属性返回0,则表示文件未被选中;否则文件已被选中。
示例: 以下示例实现了上述方法。
<h1 style="color:green;">
GeeksForGeeks
</h1>
<p id="GFG_UP" style="font-size: 15px; font-weight: bold;">
</p>
<input type="file" name="File" id="file" />
<br><br>
<button onclick="GFG_Fun()">
click here
</button>
<p id="GFG_DOWN" style="color:green; font-size: 20px; font-weight: bold;">
</p>
<script>
var up = document.getElementById('GFG_UP');
var down = document.getElementById('GFG_DOWN');
var file = document.getElementById("file");
up.innerHTML = "Click on the button to see"
+ " if any file is selected";
function GFG_Fun() {
if(file.files.length == 0 ){
down.innerHTML = "No files selected";
} else {
down.innerHTML = "Some file is selected";
}
}
</script>
输出:
方法2
在jQuery中使用 element.files.length 属性来检查文件是否被选择。如果element.files.length属性返回0,则文件未被选择,否则文件已被选择。
示例: 这个示例实现了上述方法。
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
</script>
<h1 style="color:green;">
GeeksForGeeks
</h1>
<p id="GFG_UP"
style="font-size: 15px; font-weight: bold;">
</p>
<input type="file"
name="File"
id="file" />
<br><br>
<button onclick="GFG_Fun()">
click here
</button>
<p id="GFG_DOWN"
style="color:green; font-size: 20px; font-weight: bold;">
</p>
<script>
var up = document.getElementById('GFG_UP');
var down = document.getElementById('GFG_DOWN');
up.innerHTML = "Click on the button to see"
+ " if any file is selected";
function GFG_Fun() {
if ($('#file')[0].files.length === 0) {
down.innerHTML = "No files selected";
} else {
down.innerHTML = "Some file is selected";
}
}
</script>
输出: