Question

I have three file inputs as follows,

A File : <input type="file" name="AFile" id="AFile" />
B File: <input type="file" name="BFile" id="BFile" />
C File : <input type="file" name="CFile" id="CFile" />

I've used the following jQuery function to auto upload the 3 files all at once when selected,

$("#AFile" && "#BFile" && "#CFile").change(function() { 
document.getElementById("UploadFile").submit();
}); 

But as this works only for CFile selection and does not check if AFile and BFile are selected or not.

Logically I wanted it to work like A AND B AND C.

Was it helpful?

Solution 2

Try something like

var files = $("#AFile,#BFile,#CFile").change(function () {
    var count = files.filter(function () {
        return this.value.length
    }).length;
    if (count == files.length) {
        document.getElementById("UploadFile").submit();
    }
});

OTHER TIPS

There isn't a way to detect that all 3 have changed. Changing the selector will not add that functionality, so you have to do it yourself. This should do the trick...

var files = {
    AFile: false,
    BFile: false,
    CFile: false
};

$("#AFile, #BFile, #CFile").on("change", function() {
    files[this.id] = !!this.value.length;
    for (var i in files) {
        if (!files[i]) return;
    }
    // they have all changed - do something here
});

That will flag when each of the inputs changes, and you can add whatever code you need at the end of the function, and it will only fire when all 3 have changed.

I put the loop in to check files so that you can easily extend it to add more file inputs if needed.

$("#AFile #BFile #CFile")

will be AND operator in selectors which mean select a element with all 3 ids i.e. AFile AND BFile AND CFile while

$("#AFile, #BFile, #CFile")

mean OR operator, which means select all elements with id as AFile OR BFile OR CFile

Just a side note in HTML element should have single and unique id. #AFile" && "#BFile" && "#CFile (which means elements with id AFile AND BFile AND CFile) doesnt make sense in world of valid HTML

If you want to select all elements with id #AFile, #BFile and #CFile then you should use

$("#AFile, #BFile, #CFile).change(function() { 
   document.getElementById("UploadFile").submit();
});

You can use comma , to separate multiple selectors:

$("#AFile,#BFile,#CFile").change(function() { 
    document.getElementById("UploadFile").submit();
}); 
$("#AFile","#BFile", "#CFile").change(function() { 
document.getElementById("UploadFile").submit();
}); 

Try this:

$("#AFile , #BFile , #CFile").change(function() { 
   var $this = $(this);
   $this.addClass('changed');
   if($this.each(function(){
      return this.className == 'changed';
   }){
      document.getElementById("UploadFile").submit();
  }
}); 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top