Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count selected files

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?
like image 483
Linas Avatar asked Feb 10 '12 18:02

Linas


Video Answer


2 Answers

pure javascript:

document.getElementById("my_id").addEventListener("change", function() {
    console.log(this.files.length);
});
like image 157
Lloyd Avatar answered Oct 14 '22 09:10

Lloyd


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/

like image 20
dku.rajkumar Avatar answered Oct 14 '22 09:10

dku.rajkumar