so i have an <input type="file" id="image">
. I use querySelector to get it, let’s say:
const selectImg = document.querySelector("#image");
Then i add an input listener to it:
image.addEventListener("input", () =>{
let isFileExists = image.files.length;
console.log(isFileExists);
});
The first time i select a file, it works fine, the console prints out 1. But then, if i open the input file again, but not select anything and click "Cancel", the console prints out 0, even when the input file already had a file in it.
Can anyone explain it to me?
2
Answers
You can use ‘change’ event:
The specs have this to say on the matter:
(Note that update the file selection is where both
input
andchange
events are fired).So it seems that on your system, the input is cleared when you click "Cancel" in the prompt, as is allowed per the note. However beware that not all users will have this behavior, for instance on my macOS system I get
cancel
eventcancel
eventcancel
eventinput
+change
eventcancel
eventcancel
eventcancel
eventcancel
eventAs you can see, it’s a mess, but by listening at the
cancel
event, you can yourself clear the input (input.value = null
) and get a relatively standard behavior.But if the input selection is not cleared visually, and the
input
event fires, that would be a browser bug and you may want to report it to your browser’s vendor.