1

When user clicks an input[type="file"] it shows them a popup to choose a file

User may choose one and click OK or click cancel

When they click OK - it's onChange event, great

When cancel - there is no event or I don't know about it

So the question is:

What event is fired when user clicks cancel or how to determine differently that no files have been chosen AFTER clicking cancel?

Gena
  • 1,497
  • 1
  • 13
  • 18
  • Examine the `files` property of the input element and check its length. Or the `value` – ADyson Sep 15 '19 at 17:49
  • Possible duplicate of [How to determine if user selected a file for file upload?](https://stackoverflow.com/questions/46219/how-to-determine-if-user-selected-a-file-for-file-upload) – ADyson Sep 15 '19 at 17:50
  • @ADyson when to examine? I don't have any events when the user clicks cancel – Gena Sep 15 '19 at 17:53
  • Probably makes sense to do it at the time you validate your form, before submitting it – ADyson Sep 15 '19 at 17:59
  • I want to do it when the blur event fires, but the problem is that it fires right after opening the popup, not after you closing it by clicking cancel – Gena Sep 15 '19 at 18:29

2 Answers2

4

When the user initiates the file upload by clicking on the file input, you can add an event listener to the browser window to see when it re-gains focus. Since the system dialog is blocking/modal, the window will only re-gain focus when the dialog is dismissed.

In the event handler function, you can check to see if the value of the input changed. At the end, remove the focus event handler so it doesn't trigger from normal alt-tab or window focus events:

file.addEventListener("click", function () {
  window.onfocus = function () {
    console.log("The window was re-focused from the file input dialog");

    if (file.files.length === 0) {
      console.log("NO files were added");
    } else {
      console.log("Files were added");      
    }

    // Remove the handler
    window.onfocus = null;
  };
});
<input id="file" type="file">
skyline3000
  • 7,639
  • 2
  • 24
  • 33
0

Just check the length of the files property of the file selector node:

const input = document.querySelector ('input[type="file"]')
if(input.files.length === 0){
  //The user hasn't selected any files...
}

To detect changes, just add an event listener to the change event:

const input = document.querySelector ('input[type="file"]')
input.addEventListener('change', ()=>{
  if(input.files.length === 0){
    //Cancel clicked
  } else {
    //The user selected some files just now
  }
})
FZs
  • 16,581
  • 13
  • 41
  • 50
  • When should I do this? I don't have any events when user clicks cancel – Gena Sep 15 '19 at 17:59
  • Unfortunately, onChange event doesn't fire when you didn't choose anything and click cancel (Chrome, MacOS) But I suspect it works the same way everywhere – Gena Sep 15 '19 at 18:04