Open In App

How to check input file is empty or not using JavaScript/jQuery ?

Given an HTML document containing an input element, the task is to check whether an input element is empty or not with the help of JavaScript. 

These are the two approaches to check input file is empty or not using JavaScript/jQuery:



Approach 1: Using element.files.length property in JavaScript

To check file is selected or not. If element.files.length property returns 0 then the file is not selected otherwise the file is selected.



 Example: This example implements the above approach. 




<!DOCTYPE html>
<html lang="en">
 
<head>
    <title>Check If Inputs are Empty using jQuery</title>
 
<body>
    <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>
        let up = document.getElementById('GFG_UP');
        let down = document.getElementById('GFG_DOWN');
        let 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>
</body>
 
</html>

Output:

Approach 2: Using element.files.length property in jQuery

To check the file is selected or not. If element.files.length property returns 0 then the file is not selected otherwise file is selected. 

Example: This example implements the above approach. 




<!DOCTYPE html>
<html lang="en">
 
<head>
    <title>Check If Inputs are Empty using jQuery</title>
 
<body>
    <script src=
    </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>
        let up = document.getElementById('GFG_UP');
        let 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>
</body>
 
</html>

Output:


Article Tags :