Dario Zadro
Dario Zadro

Reputation: 1284

JQuery Loop Through all File Input Fields to Get Size

I'm trying to loop through all file input fields and set an error message if any are over 5MB as a first step to form validation.

I'm using a click event on the submit button. The problem is that "key" is not defined.

This form can have up to 10 file input fields, added via AJAX called images[]

        /* loop through all file inputs to check size */
        $("#my-form").find("input[type='file']").each(function(key, value) {
            var el = this.files[key];
            if(el.size > 5242880 || el.fileSize > 5242880) {
                errorMessage = 'Files must be less than 5MB.';
            }
        });

If I use this.files[0] I can get the first field's size, but having trouble looping through all elements. Appreciate your input or other solutions. Thanks much!

Upvotes: 5

Views: 13394

Answers (1)

Rocky
Rocky

Reputation: 547

You could do this

$("#my-form").find("input[type=file]").each(function(index, field){
   const file = field.files[0];
   if(file.size > 5242880 || file.fileSize > 5242880) {
      errorMessage = 'Files must be less than 5MB.';
   }
});

Here is a fiddle: https://jsfiddle.net/kmm67nLz/

For file inputs with multiple attribute

$("#my-form").find("input[type=file]").each(function(index, field){
  for(var i=0;i<field.files.length;i++) {
    const file = field.files[i];
    if(file.size > 5242880 || file.fileSize > 5242880) {
      errorMessage = 'Files must be less than 5MB.';
      alert(errorMessage);
    }
  }
});

Here is a fiddle: https://jsfiddle.net/kmm67nLz/1/

The second one is perfect to use in any of single or multiple file input.

Upvotes: 8

Related Questions