Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 :

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 />
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading