Question

I feel a little silly posting this, as it seems pretty straight forward from what I've been reading, but I don't know why I'm always seeing 1 as the value for files.length.

<html>
<head>
<script src="http://code.jquery.com/jquery-1.7.2.js" type="text/javascript"></script>
<script>
    $(document).ready(function() {
        var button = $('#button');
        button.click(function(){    
           var files = $('#files');
           alert(files.length);
        });
     });
</script>
</head>
<body>
  <form>
    <input type="file" id="files" multiple="" />
    <input type="button" id="button" value="Upload" />
  </form>
</body>
</html>         
Was it helpful?

Solution

Change the alert line to:

alert(files[0].files.length);

This works because what you are trying to do is get the files attribute of the input DOM element which is the FileList object. You then want the length attribute of the of the FileList which will tell you how many objects were selected. You are first selecting the input element with jQuery, however the result of a jQuery selection like $("#files") is a jQuery collection, you want the underlying DOM object for the input element because only that has the files attribute. Every jQuery object masquerades as an Array so you can use standard array dereferencing to get the underlying DOM element. (See: http://api.jquery.com/get/ )

Try It!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top