11

I have a html5 application that makes use of the file API, using an element. I am able to respond when the user selects a file. I would like to be able to do something if the user cancels the file choice. However, I can find no event that is fired on the input element if the user clicks on the cancel rather than ok button in the file chooser dialogue.

Is there some event fired on 'cancel' that I am missing, or should I re-architect my app to not need this?

drdozer
  • 329
  • 1
  • 3
  • 10

6 Answers6

0

There isn't really a listener to check for if a file was selected, you could get around it by setting a note in your code using the on change event like so:

var FileChoosen = false;

var inputElement = document.getElementById("inputField");
inputElement.addEventListener("change", handleFiles, false);
function handleFiles() {
  var fileList = this.files; /* now you can work with the file list */


  //Check if the layout was changed from file API:
  if(document.getElementById('fileOutput').innerHTML != "") {
    FileChoosen = true;
    setTimeout("funcCalledToCheckUserSelection()", 500);
  };


}
Chad Adams
  • 1,319
  • 1
  • 9
  • 14
0

I have the same question, the solution is surprisingly very easy ... at least in my case NW.js (Node-Webkit) fires oncancel event if user click the [cancel] button in the file chooser dialogue. You use this simple and native way if you're also on NW.js (process.version is v5.11.0).

I also tried Microsoft HTA on Windows 10, it does not fire the oncancel event.

H.C.Chen
  • 412
  • 4
  • 14
0
In react , on Change event of input field , the event has no files on cancel event, we can proceed with this assumption. Cancel event will be captured. on file selection it wont be undefined.

  handleChange = (event) => {
    console.log(event);
    console.log(event.target.files[0]);
    this.setState({
      tableDataResult: false,
    });
    if(event.target.files[0]){
      this.setState({
        csvfile: event.target.files[0],
      });
    }else{
//Cancel event called
      console.log("false");
      this.setState({
        csvfile: oldValue,
      });
    }
  };

<input
                                        style={{
                                          width: "450px",
                                          marginLeft: "15px",
                                          marginTop: "5px",
                                        }}
                                        className="csv-input"
                                        type="file"
                                        ref={(input) => {
                                          this.filesInput = input;
                                        }}
                                        name="file"
                                        placeholder={null}
                                        onChange={this.handleChange}
                                      />
Sandeep Jain
  • 1,019
  • 9
  • 13
0

Yes, we have a problem catching cancel button. There is no event. Life hack solutions is use other events: Event "focus" on file input, or "mousemove" on window. Input file field must be visible for "focus" event. With mouse event, you need to delay when catch event.

m_skipper
  • 121
  • 1
  • 3
0

In other to capture the cancel event on an input element with type="file", you can listen to the change event on the element and check whether the user has selected any files or canceled the dialog box. Follow the code snippet in JavaScript:

<input type="file" id="myFileInput">

<script>
  const fileInput = document.getElementById('myFileInput');

  fileInput.addEventListener('change', event => {
    const files = event.target.files;
    
    if (files.length > 0) {
      // The user selected some files
      console.log('Files selected:', files);
    } else {
      // The user canceled the dialog box
      console.log('Dialog box canceled');
    }
  });
</script>

Note that I first select the input element with id="myFileInput". I then added an event listener for the change event on the element. Inside the event listener, I check the files property of the event.target object to see if the user has selected any files. If the files array has a length greater than 0, we know that the user has selected some files, and we log them to the console. If the file array has a length of 0, it means the user has canceled the dialog box, and log a message to the console indicating that the dialog box was canceled.

Abandev
  • 95
  • 1
  • 1
  • 14
-1

When user clicks cancel, change event triggers again. Thats works for me;

        $('#attachedFiles').bind("change", function () {
            var file = this.files[0];
            if (file) {
                // if file selected, do something
            } else {
                // if user clicks 'Cancel', do something
            }
        });
David
  • 7,005
  • 2
  • 22
  • 29
E-D
  • 115
  • 2
  • 8
  • 8
    Which browsers throw a change event on file input cancel? Doesn't work for me. – Patrick Rudolph Apr 07 '15 at 13:28
  • for more explications : This command only works for the Google Chrome browser. - **And this is normal** - Google Chrome passed the polical to let the user choose to delete the file, and not just cancel the -`browse...`- It's a matter of **policals browsers** others just have to cancel the click. The filename display in the file input type is consistent depending of browsers. At a google chrome cancellation removes the file and the filename in the input type file while others do nothing. Voilà. – maliness Sep 27 '16 at 16:07
  • I'm with @PatrickRudolph - I am using Firefox and change is not triggering when user clicks cancel. Patrick did you find a solution? – Noitidart Sep 30 '17 at 20:07
  • 1
    Change event is not triggered when cancel is clicked. Browser: edge – Orlando Helmer Jan 20 '21 at 08:38