Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App
geeksforgeeks
Browser
Continue

Related Articles

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

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

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

Approach 1: Use element.files.length property 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. 

html




<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>

Output:

 

Approach 2: Use 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. 

html




<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>
    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>

Output:

 


My Personal Notes arrow_drop_up
Last Updated : 19 Dec, 2022
Like Article
Save Article
Similar Reads
Related Tutorials