Html input file selection event not firing upon selecting the same file
To always trigger the change
event when re-selecting the same file on <input type="file">
, you need to clear the input value after each change.
This works because setting this.value = ''
reinitializes the input to receive the same file.
Understand the file input 'change' event
The change
event of file input is triggered whenever a new file is selected. However, selecting the same file doesn't trigger the event because the browser doesn't detect a change.
Resetting the input value
The trick to circumvent this is to reset the input value after every file selection.
The exceptional behavior of Firefox
Also note that FireFox might not recognize that value was reset and needs an explicit return false;
.
Working with multiple files
In case your fileInput
supports multiple file selection (<input type="file" multiple>
), remember that the change
event provides a FileList
object, not a single File
.
Advanced tips and tricks
Ensure enctype is set in forms
Ensure that your form has enctype='multipart/form-data'
for proper handling of file uploads.
Exploring the 'input' event for file uploads
While change
event is useful in most scenarios, "input"
event can provide a different level of control. It's worth exploring in real-time changes scenarios.
Take note of the following nuances
- Specific to Chrome: Chrome might demand additional event handling if file selection dialog is dismissed without choosing a file.
- When file selections are cancelled: If the user clicks cancel in the file dialog,
change
event won't trigger. - Browser's security measures: Browsers display a fake path (
C:\fakepath
) when handling file input for security, but the selected file's metadata is still accessible.
Was this article helpful?