'Jquery change event to work with all fields with same class

I am trying to run jquery on changing values in multiple input fields. For example: I have 6 input type file fields. I want to set upload limit on all file fields with single jquery function.

To achieve this, I used this jquery code

 $('.image_size_check').change(function(){
     $('.image_size_check').each(function(){
        var sizeInKB = this.files[0].size/1024; //converting bytes into kb
        var sizeLimit= 200;
    
        if (sizeInKB >= sizeLimit) {
            alert("Max file for image is 200KB");
            $(this).val('');
        }
    });
});

But issue with this code is that, this code runs only when I make change in first file field. When I select file on second field, third field and so on, then this code doesn't work.

How do I make this code run (without using onchange event at attribute of input field) on selecting file on every file field present on page



Solution 1:[1]

You need to check the console errors. It clearly tells you the issues. When you loop through the inputs, only the first input has value while others doesn't have any value due to which this.files is null and hence this.files[0].size causes error:

$('.image_size_check').change(function() {
  $('.image_size_check').each(function() {
    if (this.files.length) {
      var sizeInKB = this.files[0].size / 1024; //converting bytes into kb
      var sizeLimit = 200;

      if (sizeInKB >= sizeLimit) {
        alert("Max file for image is 200KB");
        $(this).val('');
      }
    }
  });
});
Hello <input class="image_size_check" type="file" /><br />Hello <input class="image_size_check" type="file" /><br />Hello <input class="image_size_check" type="file" /><br />Hello <input class="image_size_check" type="file" /><br />Hello <input class="image_size_check"
  type="file" /><br />Hello <input class="image_size_check" type="file" /><br />Hello <input class="image_size_check" type="file" /><br />Hello <input class="image_size_check" type="file" /><br />Hello <input class="image_size_check" type="file" /><br />Hello
<input class="image_size_check" type="file" /><br />

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 K K