How to Count the Number of Selected Files using jQuery

When you want to allow the user to select multiple files to upload, Files number validation is very useful. It helps to prevent user to select multiple files beyond the upload limit. Before submitting the selected files to the server-side script, it always a good idea to validate the number of files on the client-side.

To implement client-side files number validation, you need to count the number of selected files. You can count selected files using JavaScript and jQuery. The example code snippet helps to count the number of the selected image files and validate the files upload limit using jQuery.

HTML
The multiple attribute allow to select multiple files.

<input type="file" id="image" name="image[]" multiple>

JavaScript
Include jQuery library.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

The selected images number is counted on the jQuery change event of the file input field. If the number of the selected files are cross the predefined limit, an error message will be shown.

<script>
var limit = 5;
$(document).ready(function(){
    $('#image').change(function(){
        var files = $(this)[0].files;
        if(files.length > limit){
            alert("You can select max "+limit+" images.");
            $('#image').val('');
            return false;
        }else{
            return true;
        }
    });
});
</script>

Leave a reply

keyboard_double_arrow_up