Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 526
Dario Zadro Avatar asked May 16 '17 00:05

Dario Zadro


People also ask

How to loop through all input fields jQuery?

Approach 1: In this approach, we will iterate over every input type which is of text type by using input[type=text] as the selector. Next, we will use the each() method to iterate over the inputs to display the values or perform any operation as needed. Syntax: $("#id input[type=text]").

How to get value of each input in jQuery?

Answer: Use the jQuery val() Method You can simply use the jQuery val() method to get the value in an input text box. Try out the following example by entering something in the text input box and then click the "Show Value" button, it will display the result in an alert dialog box.

How to loop through array of objects in jQuery?

each(), which is used to iterate, exclusively, over a jQuery object. The $. each() function can be used to iterate over any collection, whether it is an object or an array. In the case of an array, the callback is passed an array index and a corresponding array value each time.


1 Answers

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.

like image 76
Rocky Avatar answered Sep 21 '22 20:09

Rocky