How to Limit the Maximum Files Chosen Using JavaScript?

Aug 27, 2022 . Admin



Hello dev,

This tutorial will provide an example of how to limit the maximum files chosen using javascript. let’s discuss the javascript check limit for the maximum files chosen. you'll learn how to get the limit of maximum files chosen in javascript.

We use the multiple attributes on the HTML element to allow multiple file uploads in our HTML forms. the input element does not provide any attribute to specify how many files can be uploaded at once, input.files property return a FileList object .

So, let's see bellow solution:

Example :
index.html
<!DOCTYPE html>
<html>
    <head>
        <title>How to Limit the Maximum Files Chosen Using JavaScript? - MyWebtuts.com</title>
    </head>
    <body>
        <h1>How to Limit the Maximum Files Chosen Using JavaScript? -  MyWebtuts.com</h1>
        <input type="file" id="profile" multiple>
        <script type="text/javascript">
            const input = document.querySelector('#profile');

            // Listen for files selection
            input.addEventListener('change', (e)=> {
                // Retrieve all files
                const files = input.files;

                // Check files count
                if(files.length > 2) {
                    document.write("Only 2 files are allowed to upload.");
                    return;  
                }
                else{
                    document.write("continue uploading."); 
                }
            });
        </script>
    </body>
<html>
Output:
Only 2 files are allowed to upload.
I hope it will help you...
#Javascript