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.