Difficulty understanding code which retrieves a filename from a file control

Viewed 30

I have this code in a project. I understand that it outputs the file from a file input control. The issue is that I don't understand the working of var filename = e.target.files[0].name. Please help me out, if you can.

$(document).ready(function() {
  $('input[type="file"]').change(function(e) {
    var fileName = e.target.files[0].name;
    $('#choose').html(fileName);
  });
});
1 Answers

Breaking the line e.target.files[0].name down in to sections:

  • e is the Event object passed to the jQuery event handler function as an argument.
  • target is the property which contains a reference to the element which raised the event
  • files is a collection of the files selected within the input type="file" control. If the control has the multiple attribute set on it, it's possible for there to be more than 1 file selected, in which case you would need a loop.
  • [0] retrieves only the first selected file from the files collection - in the same manner as you access an array by index.
  • name gets the filename of that file.
Related