Home > other >  Jquery change event to work with all fields with same class
Jquery change event to work with all fields with same class

Time:04-28

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

CodePudding user response:

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  type="file" /><br />Hello <input  type="file" /><br />Hello <input  type="file" /><br />Hello <input  type="file" /><br />Hello <input 
  type="file" /><br />Hello <input  type="file" /><br />Hello <input  type="file" /><br />Hello <input  type="file" /><br />Hello <input  type="file" /><br />Hello
<input  type="file" /><br />

  • Related