$("#imageupload")[0]
Basically, we don't need to use the brackets because when using the ID Selector, in the ideal world, it's supposed to be only one element match the given ID. We used it here just to make sure there's no chance for error occur. You could remove that [0] in case there's exactly one element in your website has that ID. Like this:
var fname = $("#imageupload").prop('files')[0].name;
// or
var fname = document.getElementById('fileItem').files[0].name //without jQuery
This is the demo: https://codesandbox.io/s/kx5q2x24xv
files[0] and files[i]
The files here is called a FileList object, and:
An object of this type is returned by the files property of the HTML
element; this lets you access the list of files selected with
the <input type="file"> element.
In other words:
All element nodes have a files array on them which allows
access to the items in this list.
We use the bracket with the index in order to access the specific element of that array.
This example iterates over all the files selected by the user using an input element:
// fileInput is an HTML input element: <input type="file" id="myfileinput" multiple>
var fileInput = document.getElementById("myfileinput");
// files is a FileList object (similar to NodeList)
var files = fileInput.files;
var file;
// loop through files
for (var i = 0; i < files.length; i++) {
// get item
file = files.item(i);
//or
file = files[i];
alert(file.name);
}
For more information: FileList
$("#imageupload")is asking jquery to select all elements that have the id ofimageupload. It is possible zero or more elements will be found with that id. Thus jquery returns an array.[0]means the first element in the found array. Then you ask for the first filefiles[0]in that input element. If a loop, meaning multiple files, you use a variable and ask for file at the variable locationfiles[i]whereiis the variable. Whenever you see square brackets in JavaScript, and most other languages but not all, it means you are accessing an element from an array.