16

I have very simple form, with input like this:

<input id="my_id" multiple="true" type="file" name="image_name[]" />

Now i have two questions:

  1. how can i count selected files with jQuery or pure JavaScript?
  2. how can i limit file selection to, let's say 10, because now it's infinite?
Brandan
  • 14,735
  • 3
  • 56
  • 71
Linas
  • 4,380
  • 17
  • 69
  • 117
  • [this answer](http://stackoverflow.com/questions/6171013/javascript-get-number-of-files-and-their-filenames-from-input-multiple-elemen) might be useful for you – driangle Feb 10 '12 at 18:12

3 Answers3

23

in case of input type file the value is stored in array as files with key name.

$('input#my_id').change(function(){
    var files = $(this)[0].files;
    if(files.length > 10){
        alert("you can select max 10 files.");
    }else{
        alert("correct, you have selected less than 10 files");
    }
});

fiddle example : http://jsfiddle.net/nze2B/3/

dku.rajkumar
  • 18,414
  • 7
  • 41
  • 58
5

pure javascript:

document.getElementById("my_id").addEventListener("change", function() {
    console.log(this.files.length);
});
Lloyd
  • 8,204
  • 2
  • 38
  • 53
0

using vanila js

if(document.getElementById("my_id").files.length > 10){
   console.log("10 files can be uploaded at a time.");                   
}
  • Please don't post only code as answer, but also provide an explanation what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes. – Tyler2P Aug 05 '21 at 17:05