Accessing Input File Upload Field in JavaScript - Stack Overflow
Accessing Input File Upload Field in JavaScript - Stack Overflow
Asked
4 years, 5 months ago Modified
4 years, 5 months ago Viewed
6k times
$("#imageupload")[0]
files[0]
files[i]
javascript
Your privacy
Share Improve this question Follow asked Oct 4, 2018 at 4:25
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose
information in accordance with our Cookie Policy. Sachin
1,616 1 22 57
$("#imageupload") is asking jquery to select all elements that have the id of imageupload . It is
possible zero or more elements will be Necessary cookies
found with that id.only
Thus jquery returns an array. [0] means the
first element in the found array. Then you ask for the first file files[0] in that input element. If a loop,
meaning multiple files, you use a variable and ask for file at the variable location files[i] where i is
Customize settings
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.
– CodingYoshi
Oct 4, 2018 at 4:40
Report this ad
Sorted by:
1 Answer
Highest score (default)
$("#imageupload")[0]
1
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:
// or
var fname = document.getElementById('fileItem').files[0].name //without jQuery
In other words:
Necessary cookies only
This example iterates over all the files selected by the user using an input element:
var file;
// get item
file = files.item(i);
//or
file = files[i];
alert(file.name);
Share Improve this answer Follow edited Oct 4, 2018 at 7:36 answered Oct 4, 2018 at 4:45
You Nguyen
9,801 4 24 51
I'm sorry, I've updated my answer. We have to access the FileList in the jQuery way.
– You Nguyen
Oct 4,
2018 at 7:36
But you have done it with another way $("#imageupload").prop('files')[0].name; . I still couldn't
get my exact answer - why do we use [0] after id selector.
– Sachin
Oct 5, 2018 at 4:43
if that is the case of an array then as jquery returns files array then why [1] does not work if I have some
another file upload field with same id?
– Sachin
Oct 5, 2018 at 4:44
Your privacy
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose
information in accordance with our Cookie Policy.
Customize settings