1

Everything is in the title: how can I check if a file is loaded to <input type="file"> ?

<input type="file" id="document-file" />
<input type="submit" id="document-send" />


<script type="text/javascript">
    $('#document-send').click(function(event){
        event.preventDefault();

        var files = $("#document-file");
        console.log(files.length);
    }
</script>

files.length always returns me 1 even if no file is loaded.

Ghilas BELHADJ
  • 13,412
  • 10
  • 59
  • 99

3 Answers3

3

You can check the files property of the element, not the jQuery object:

var files = $("#document-file")[0].files;
tymeJV
  • 103,943
  • 14
  • 161
  • 157
3

You could just try to read if the input has a value:

if(document.getElementById("document-file").value != ""){
    // do stuff here
}

If it does, theres a file, if its empty there isn't. It's backwards compatible with browsers that don't support fileReaders.

somethinghere
  • 16,311
  • 2
  • 28
  • 42
1

You want to check the .val() of the input, then check the .length of that value.

DEMO

Here is how I did it in fiddle.

$('button').click(function(){
    var files = $("#document-file").val();
    if(files.length > 0){
         $('body').append(files + '<br />');
    } else {
         $('body').append('No File <br />');
    }
});

I hope this helps!

wrxsti
  • 3,434
  • 1
  • 18
  • 30