1

I have a form with multiple input file types. I want to check if any of the inputs have a file selected. I have tried $('.multi').val() but this is not working.

http://jsfiddle.net/hbdyresq/

$('.bt').on('click', function() {
  var filesSelected = $('.multi').val();
  console.log(filesSelected)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="file" name="File" class="multi" />
<input type="file" name="File" class="multi" />
<input type="file" name="File" class="multi" />
<input type="file" name="File" class="multi" />
<input type="file" name="File" class="multi" />
<input type="file" name="File" class="multi" />
<button class="bt" type="button">button</button>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
user974802
  • 3,397
  • 10
  • 26
  • 29
  • You can use one input for multiple files: https://www.w3schools.com/tags/att_input_multiple.asp – Niels Prins Mar 12 '20 at 13:52
  • If you read the docs for .val() you will see it picks the first input from the jQuery collection. So you will need to loop in some manner to check them all. – epascarello Mar 12 '20 at 13:54
  • Does this answer your question? [check if a file is loaded to ](https://stackoverflow.com/questions/25017185/check-if-a-file-is-loaded-to-input-type-file) – Heretic Monkey Mar 12 '20 at 13:58

1 Answers1

1

To check if any of the file inputs have a file selected you can use filter() to retrieve only those where the files.length is not zero:

$('.bt').on('click', function() {
  var filesSelected = $('.multi').filter((i, el) => el.files.length).length != 0;      
  console.log(filesSelected);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="file" name="File" class="multi" />
<input type="file" name="File" class="multi" />
<input type="file" name="File" class="multi" />
<input type="file" name="File" class="multi" />
<input type="file" name="File" class="multi" />
<input type="file" name="File" class="multi" />
<button class="bt" type="button">button</button>
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339