Input selector like file.files not working in jQuery

I am trying to get information about a download file in HTML input with the following code:

$(document).ready(function() {
  $('#btn').on('click', function() {
    file_size = $("#my_file").files[0].size;
    alert(file_size);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <input id="my_file" type="file" name="my_name" />
  <input id="btn" type="button" />
</form>
Run codeHide result

But this does not work, and the console returns: $("#my_file").files is undefined

+5
source share
3 answers

$("#my_file")is a jQuery object, and the jQuery object has no property files...

To get the DOM element from jQuery do

($("#my_file"))[0].files[0].size

As an additional note, if you did not select any file, ($("#my_file"))[0].files[0]it gives you undefinedand ($("#my_file"))[0].files[0].sizewill cause an error.
You are advised to add a check ...

if (($("#my_file"))[0].files.length > 0) {
    file_size = ($("#my_file"))[0].files[0].size
} else {
    // no file chosen!
}
+33
source

The jQuery object has no property files, you can use the old method getElementByIdor jQuery getto select the DOM Element object.

$(document).ready(function() {
  $('#btn').on('click', function() {
    file_size = document.getElementById("my_file").files[0].size;
    alert(file_size);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <input id="my_file" type="file" name="my_name" />
  <input id="btn" type="button" />
</form>
Run codeHide result
+1
source

$(document).ready(function() {
  $('#btn').on('click', function() {
    file_size = document.getElementById("my_file").files[0].size;
    alert(file_size);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <input id="my_file" type="file" name="my_name" />
  <input id="btn" type="button" />
</form>
Run codeHide result
-3
source

All Articles